import { defineStore } from "pinia";
import { login as loginApi } from "@/api/auth";
import { AUTH_TOKEN_KEY, AUTH_USER_KEY } from "@/utils/constants";
import type { UserProfile } from "@/types/api";

interface AuthState {
  token: string;
  user: UserProfile | null;
}

export const useAuthStore = defineStore("auth", {
  state: (): AuthState => ({
    token: "",
    user: null
  }),
  getters: {
    isLoggedIn: (state) => Boolean(state.token)
  },
  actions: {
    hydrate() {
      this.token = uni.getStorageSync(AUTH_TOKEN_KEY) || "";
      const storedUser = uni.getStorageSync(AUTH_USER_KEY);
      this.user = storedUser ? JSON.parse(storedUser) : null;
    },
    async login(email: string, password: string) {
      const result = await loginApi(email, password);
      this.token = result.token;
      this.user = result.user || { email };
      uni.setStorageSync(AUTH_TOKEN_KEY, result.token);
      uni.setStorageSync(AUTH_USER_KEY, JSON.stringify(this.user));
    },
    logout() {
      this.token = "";
      this.user = null;
      uni.removeStorageSync(AUTH_TOKEN_KEY);
      uni.removeStorageSync(AUTH_USER_KEY);
      uni.reLaunch({ url: "/pages/login/index" });
    }
  }
});
