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

const api = axios.create({ baseURL: '/api' });
api.interceptors.request.use((config) => {
  const storage = localStorage.getItem('auth-storage');
  if (storage) {
    const parsed = JSON.parse(storage);
    const token = parsed?.state?.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
  }
  return config;
});

interface User {
  id: number;
  email: string;
  role: 'admin' | 'teacher' | 'student' | 'parent' | 'principal' | 'hr' | 'bursar';
  first_name: string;
  last_name: string;
}

interface AuthState {
  token: string | null;
  user: User | null;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  isAuthenticated: () => boolean;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      token: null,
      user: null,
      login: async (email: string, password: string) => {
        const res = await api.post('/auth/login', { email, password });
        const { token, user } = res.data;
        api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        set({ token, user });
      },
      logout: () => {
        delete api.defaults.headers.common['Authorization'];
        set({ token: null, user: null });
      },
      isAuthenticated: () => !!get().token,
    }),
    { name: 'auth-storage' }
  )
);

// API helper with auth
export const useApi = () => {
  const { token } = useAuthStore();
  if (token) {
    api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  }
  return api;
};

export { api };
export const apiInstance = api;
export default api;