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';
import { useTaskQueueStore } from './taskQueue';

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null);
  const accessToken = ref<string | null>(null);
  const refreshToken = ref<string | null>(null);
  let autoAccountSyncTimer: ReturnType<typeof setInterval> | null = null;
  let autoAccountSyncTimeout: ReturnType<typeof setTimeout> | null = null;
  let autoAccountSyncRunning = false;

  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;
    stopAutoAccountSync();
    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;
    
    startAutoAccountSync();
    
    return result;
  }
  
  async function enqueueSyncAccountTasks(): Promise<void> {
    if (!isAuthenticated.value || autoAccountSyncRunning) return;
    autoAccountSyncRunning = true;

    try {
      const taskStore = useTaskQueueStore();
      const accounts = await accountsApi.getAccounts();

      for (const account of accounts) {
        await taskStore.syncAccount(account.id, account.accountName);
      }
    } catch (error) {
      console.warn('[Auth] Auto account sync failed:', error);
    } finally {
      autoAccountSyncRunning = false;
    }
  }

  function startAutoAccountSync(initialDelay = 5000) {
    stopAutoAccountSync();

    autoAccountSyncTimeout = setTimeout(() => {
      enqueueSyncAccountTasks();
    }, initialDelay);

    const intervalMs = 10 * 60 * 1000;
    autoAccountSyncTimer = setInterval(() => {
      enqueueSyncAccountTasks();
    }, intervalMs);
  }

  function stopAutoAccountSync() {
    if (autoAccountSyncTimeout) {
      clearTimeout(autoAccountSyncTimeout);
      autoAccountSyncTimeout = null;
    }
    if (autoAccountSyncTimer) {
      clearInterval(autoAccountSyncTimer);
      autoAccountSyncTimer = null;
    }
  }

  // 注册
  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();
      
      startAutoAccountSync();
      
      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();
          
          startAutoAccountSync();
          
          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,
  };
});
