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

interface AdminState {
  user: User | null;
  loading: boolean;
  login: (username: string, password: string, rememberMe?: boolean) => Promise<void>;
  logout: () => Promise<void>;
  checkAuth: () => Promise<void>;
}

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

  login: async (username, password, rememberMe?) => {
    const user = await api.login(username, password, undefined, 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 });
    }
  },
}));
