import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import api from '@/lib/api';

interface User { id: string; name: string; email: string; role: string; }
interface Tenant { id: string; name: string; plan: string; }

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

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      tenant: null,
      accessToken: null,
      refreshToken: null,

      login: async (email, password) => {
        const { data } = await api.post('/auth/login', { email, password });
        localStorage.setItem('accessToken', data.accessToken);
        localStorage.setItem('refreshToken', data.refreshToken);
        set({ user: data.user, tenant: data.tenant, accessToken: data.accessToken, refreshToken: data.refreshToken });
      },

      logout: async () => {
        try { await api.post('/auth/logout'); } catch {}
        localStorage.clear();
        set({ user: null, tenant: null, accessToken: null, refreshToken: null });
      },

      isAuthenticated: () => !!get().accessToken && !!get().user,
    }),
    { name: 'manutix-auth', partialize: (s) => ({ user: s.user, tenant: s.tenant, accessToken: s.accessToken, refreshToken: s.refreshToken }) },
  ),
);
