import { create } from 'zustand';
import { authApi, type User, type LoginResponse } from '@/api/endpoints/auth';

interface AuthState {
  user: User | null;
  token: string | null;
  loading: boolean;
  mfaRequired: boolean;
  mfaSetup: boolean;
  totpUri: string | null;

  login: (username: string, password: string, totp?: string) => Promise<LoginResponse>;
  logout: () => Promise<void>;
  checkAuth: () => Promise<void>;
  setToken: (token: string) => void;
}

export const useAuthStore = create<AuthState>((set, get) => ({
  user: null,
  token: localStorage.getItem('t'),
  loading: true,
  mfaRequired: false,
  mfaSetup: false,
  totpUri: null,

  login: async (username, password, totp) => {
    const res = await authApi.login(username, password, totp);
    if (res.mfa_required) {
      set({ mfaRequired: true, mfaSetup: !!res.mfa_setup, totpUri: res.totp_uri || null });
      return res;
    }
    if (res.token && res.user) {
      localStorage.setItem('t', res.token);
      set({ token: res.token, user: res.user, mfaRequired: false, mfaSetup: false, totpUri: null });
    }
    return res;
  },

  logout: async () => {
    try { await authApi.logout(); } catch {}
    localStorage.removeItem('t');
    set({ user: null, token: null, mfaRequired: false });
  },

  checkAuth: async () => {
    const token = get().token;
    if (!token) { set({ loading: false }); return; }
    try {
      const user = await authApi.me();
      set({ user, loading: false });
    } catch {
      localStorage.removeItem('t');
      set({ token: null, user: null, loading: false });
    }
  },

  setToken: (token) => {
    localStorage.setItem('t', token);
    set({ token });
  },
}));
