import { create } from 'zustand';
import type { User } from '../types';
import * as api from '../api';

interface AuthState {
  user: User | null;
  loading: boolean;
  login: (username: string, password: string, captchaToken?: string, rememberMe?: boolean) => Promise<void>;
  logout: () => Promise<void>;
  checkAuth: () => Promise<void>;
  changePassword: (oldPwd: string, newPwd: string) => Promise<void>;
  refreshUser: () => Promise<void>;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: null,
  loading: true,

  login: async (username, password, captchaToken?, rememberMe?) => {
    const user = await api.login(username, password, captchaToken, rememberMe);
    set({ user });
  },

  logout: async () => {
    await api.logout();
    set({ user: null });
  },

   checkAuth: async () => {
    try {
      const token = localStorage.getItem('auth_token');
      if (!token) { set({ user: null, loading: false }); return; }
      const user = await api.getUser();
      set({ user, loading: false });
    } catch (error: any) {
      if (error?.message?.includes('401') || error?.message?.includes('Unauthorized')) {
        localStorage.removeItem('auth_token');
      }
      set({ user: null, loading: false });
    }
  },

  changePassword: async (oldPwd, newPwd) => {
    await api.changePassword(oldPwd, newPwd);
  },

  refreshUser: async () => {
    try {
      const user = await api.getUser();
      set({ user });
    } catch (error) {
      console.error('Failed to refresh user:', error);
    }
  },
}));
