import { defineStore } from "pinia";
import http, { clearAuth, saveTokens } from "@/api/http";
let accountRequest: Promise<Record<string, any>> | null = null;
export const useAuthStore = defineStore("web-auth", {
  state: () => ({
    profile: JSON.parse(localStorage.getItem("web_profile") || "null") as {
      id: string;
      uid: string;
      username?: string;
      account: string;
      avatar_url?: string;
    } | null,
    account: null as Record<string, any> | null,
    authenticated: Boolean(localStorage.getItem("web_access_token")),
    loading: false,
  }),
  actions: {
    async login(account: string, password: string) {
      this.loading = true;
      try {
        const { data } = await http.post("/auth/login", { account, password });
        saveTokens(data.data);
        this.profile = data.data.user;
        this.authenticated = true;
        await this.loadAccount();
      } finally {
        this.loading = false;
      }
    },
    async loadAccount() {
      if (!this.authenticated) return;
      if (!accountRequest)
        accountRequest = http
          .get("/account")
          .then(({ data }) => data.data as Record<string, any>)
          .finally(() => (accountRequest = null));
      this.account = await accountRequest;
    },
    updateCachedProfile(data: Record<string, any>) {
      if (!this.profile) return;
      this.profile = { ...this.profile, ...data };
      localStorage.setItem("web_profile", JSON.stringify(this.profile));
    },
    async logout() {
      const refresh = localStorage.getItem("web_refresh_token");
      try {
        await http.post("/auth/logout", { refresh_token: refresh });
      } finally {
        clearAuth();
        this.profile = null;
        this.account = null;
        this.authenticated = false;
      }
    },
  },
});
