import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import axios from 'axios';

const SUPERADMIN_API = (import.meta as any).env?.VITE_SUPERADMIN_API_BASE || '/api';

export interface SuperAdminUser {
  username: string;
  role: 'super_admin_master';
}

interface AuthState {
  token: string | null;
  user: SuperAdminUser | null;
  loginPending: boolean;
  error: string | null;
  setSession: (token: string, user: SuperAdminUser) => void;
  logout: () => void;
  loginWithCredentials: (payload: { username?: string; password?: string; master_key?: string }) => Promise<void>;
}

export const useSuperAdminAuth = create<AuthState>()(
  persist(
    (set) => ({
      token: null,
      user: null,
      loginPending: false,
      error: null,
      setSession: (token, user) => set({ token, user, error: null }),
      logout: () => set({ token: null, user: null, error: null }),
      loginWithCredentials: async (payload) => {
        set({ loginPending: true, error: null });
        try {
          const res = await axios.post(`${SUPERADMIN_API}/auth/login`, payload);
          const { token, user } = res.data;
          if (!token) throw new Error('Server did not return a token');
          set({ token, user, loginPending: false, error: null });
        } catch (err: any) {
          const msg = err.response?.data?.error || err.message || 'Authentication failed';
          set({ loginPending: false, error: msg });
          throw err;
        }
      },
    }),
    { name: 'superadmin_auth' }
  )
);

export const SUPERADMIN_API_BASE = SUPERADMIN_API;
