import { defineStore } from "pinia";
import http, { clearAuth, saveTokens } from "@/api/http";

export const useAuthStore = defineStore("auth", {
  state: () => ({
    profile: JSON.parse(localStorage.getItem("admin_profile") || "null") as { id: string; username: string } | null,
    loading: false,
  }),
  getters: { authenticated: () => Boolean(localStorage.getItem("admin_access_token")) },
  actions: {
    async login(username: string, password: string) {
      this.loading = true;
      try {
        const { data } = await http.post("/auth/login", { username, password });
        saveTokens(data.data);
        this.profile = data.data.admin;
      } finally {
        this.loading = false;
      }
    },
    async logout() {
      const refreshToken = localStorage.getItem("admin_refresh_token");
      try {
        await http.post("/auth/logout", { refresh_token: refreshToken });
      } finally {
        clearAuth();
        this.profile = null;
      }
    },
  },
});
