import Cookies from 'js-cookie';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useRoute, useRouter } from "vue-router";
import { message } from 'ant-design-vue';

import { useUserStore } from './user';
import { login } from '@/api/system';
import { TokenKey as TOKEN_KEY } from "@/utils/auth";
import type { LoginInfo } from '@/api/system/model';

export const useAuthStore = defineStore('auth', () => {
  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const loginLoading = ref(false);
  const token = ref(Cookies.get(TOKEN_KEY) || null);

  function setToken(newToken: string) {
    token.value = newToken;
    Cookies.set(TOKEN_KEY, newToken);
  }

  function clearToken() {
    token.value = null;
    Cookies.remove(TOKEN_KEY);
  }

  async function authLogin(params: LoginInfo) {
    try {
      loginLoading.value = true;
      const res = await login(params);
      if (res.code === 200) {
        setToken(res.token as string);
        await userStore.fetchUserInfo();
        message.success('登录成功');
        const redirect = route.query.redirect || "/lms";
        router.replace(redirect as string);
        return res;
      } else {
        // 抛出错误，让调用方处理
        throw new Error(res.msg || '登录失败');
      }
    } catch (error) {
      throw error;
    } finally {
      loginLoading.value = false;
    }
  }

  async function logout() {
    // 在实际应用中，这里可以调用后端的退出登录接口
    // await doLogoutApi(); 
    clearToken();
    userStore.clearUserInfo();
    await router.push('/login');
    message.success('已成功退出');
  }

  return {
    token,
    loginLoading,
    authLogin,
    logout,
  };
});
