import { defineStore } from "pinia";
import userService from "@/services/userService";
import router from "@/routers";

export const useUserStore = defineStore({
  id: "user",
  state: () => ({
    user: JSON.parse(localStorage.getItem("user")),
    errorMessage: "",
  }),
  getters: {},
  actions: {
    async login(username, password) {
      //let timeout = setTimeout(this.loginac, 5000);
      this.errorMessage = "";
      this.user = null;
      let loginModel = {
        userName: username,
        password: password,
      };

      try {
        let loginResult = await userService.login(loginModel);
        if (loginResult.Result != null && loginResult.Result === 1) {
          let user = {
            Email: loginResult.Email,
            ExpiredTime: loginResult.ExpiredTime,
            ExpiredTimestamp: loginResult.ExpiredTimestamp,
            FullName: loginResult.FullName,
            Id: loginResult.Id,
            PhoneNumber: loginResult.PhoneNumber,
            RefreshToken: loginResult.RefreshToken,
            Roles: loginResult.Roles,
            Token: loginResult.Token,
            UserName: loginResult.UserName,
          };
          this.user = user;
          localStorage.setItem("user", JSON.stringify(user));
          window.location = "/";
          //router.push("/");
        } else {
          this.errorMessage = loginResult.Message;
        }
      } catch (error) {
        this.errorMessage = "Không thể kết nối tới máy chủ";
      }
    },

    async register(registerModel) {
      this.errorMessage = "";
      try {
        let result = await userService.register(registerModel);
        if (result.Result === 1) {
          // Đăng ký thành công, có thể chuyển hướng hoặc hiển thị thông báo
          return true;
        } else {
          this.errorMessage = result.Message || "Đăng ký thất bại";
          return false;
        }
      } catch (error) {
        this.errorMessage = "Không thể kết nối tới máy chủ";
        return false;
      }
    },
    async refresh() {
      //let timeout = setTimeout(this.loginac, 5000);
      this.errorMessage = "";
      let currentUser = JSON.parse(localStorage.getItem("user"));
      let refreshResult = await userService.refreshToken(
        currentUser.RefreshToken
      );

      if (refreshResult.Result != null && refreshResult.Result === 1) {
        let user = {
          Email: refreshResult.Email,
          ExpiredTime: refreshResult.ExpiredTime,
          ExpiredTimestamp: refreshResult.ExpiredTimestamp,
          FullName: refreshResult.FullName,
          Id: refreshResult.Id,
          PhoneNumber: refreshResult.PhoneNumber,
          RefreshToken: refreshResult.RefreshToken,
          Roles: refreshResult.Roles,
          Token: refreshResult.Token,
          UserName: refreshResult.UserName,
        };
        this.user = user;
        localStorage.setItem("user", JSON.stringify(user));
      } else {
        this.errorMessage = refreshResult.Message;
      }
    },
    logout() {
      this.user = null;
      localStorage.removeItem("user");
      router.push({ name: "login" });
    },
  },
});
