import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { authApi } from '@/api/auth';
import { accountsApi } from '@/api/accounts';
import type { User, LoginRequest } from '@media-manager/shared';
import { useServerStore } from './server';

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null);
  const accessToken = ref<string | null>(null);
  const refreshToken = ref<string | null>(null);

  const isAuthenticated = computed(() => !!accessToken.value && !!user.value);
  const isAdmin = computed(() => user.value?.role === 'admin');

  // 从 localStorage 恢复 token
  function loadTokens() {
    const serverStore = useServerStore();
    const serverKey = serverStore.currentServer?.url || 'default';
    accessToken.value = localStorage.getItem(`${serverKey}_accessToken`);
    refreshToken.value = localStorage.getItem(`${serverKey}_refreshToken`);
  }

  // 保存 token 到 localStorage
  function saveTokens(access: string, refresh: string) {
    const serverStore = useServerStore();
    const serverKey = serverStore.currentServer?.url || 'default';
    accessToken.value = access;
    refreshToken.value = refresh;
    localStorage.setItem(`${serverKey}_accessToken`, access);
    localStorage.setItem(`${serverKey}_refreshToken`, refresh);
  }

  // 清除 token
  function clearTokens() {
    const serverStore = useServerStore();
    const serverKey = serverStore.currentServer?.url || 'default';
    accessToken.value = null;
    refreshToken.value = null;
    user.value = null;
    localStorage.removeItem(`${serverKey}_accessToken`);
    localStorage.removeItem(`${serverKey}_refreshToken`);
  }

  // 登录
  async function login(data: LoginRequest) {
    const result = await authApi.login(data);
    saveTokens(result.accessToken, result.refreshToken);
    user.value = result.user;
    
    // 登录成功后自动刷新所有账号状态
    refreshAllAccountsInBackground();
    
    return result;
  }
  
  // 后台刷新所有账号状态（延迟执行，避免服务启动时网络不稳定导致误判）
  async function refreshAllAccountsInBackground(delay = 5000) {
    // 延迟执行，给后端服务足够的启动时间
    setTimeout(async () => {
      try {
        console.log('[Auth] Starting background account refresh...');
        await accountsApi.refreshAllAccounts();
        console.log('[Auth] Background account refresh completed');
      } catch (error) {
        // 刷新失败不应影响用户体验，静默处理
        console.warn('[Auth] Background account refresh failed:', error);
      }
    }, delay);
  }

  // 注册
  async function register(data: { username: string; password: string; email?: string }) {
    return await authApi.register(data);
  }

  // 检查认证状态
  async function checkAuth() {
    loadTokens();
    if (!accessToken.value) return false;

    try {
      user.value = await authApi.getMe();
      
      // 应用启动时自动刷新所有账号状态
      refreshAllAccountsInBackground();
      
      return true;
    } catch {
      // Token 失效，尝试刷新
      if (refreshToken.value) {
        try {
          const result = await authApi.refresh(refreshToken.value);
          const serverStore = useServerStore();
          const serverKey = serverStore.currentServer?.url || 'default';
          accessToken.value = result.accessToken;
          localStorage.setItem(`${serverKey}_accessToken`, result.accessToken);
          user.value = await authApi.getMe();
          
          // Token 刷新成功后也刷新账号状态
          refreshAllAccountsInBackground();
          
          return true;
        } catch {
          clearTokens();
        }
      }
      return false;
    }
  }

  // 退出登录
  async function logout() {
    try {
      if (refreshToken.value) {
        await authApi.logout(refreshToken.value);
      }
    } finally {
      clearTokens();
    }
  }

  // 刷新 Token
  async function refreshAccessToken() {
    if (!refreshToken.value) return false;
    try {
      const result = await authApi.refresh(refreshToken.value);
      const serverStore = useServerStore();
      const serverKey = serverStore.currentServer?.url || 'default';
      accessToken.value = result.accessToken;
      localStorage.setItem(`${serverKey}_accessToken`, result.accessToken);
      return true;
    } catch {
      clearTokens();
      return false;
    }
  }

  return {
    user,
    accessToken,
    isAuthenticated,
    isAdmin,
    login,
    register,
    logout,
    checkAuth,
    refreshAccessToken,
    clearTokens,
  };
});
