import { create } from 'zustand';

export interface Tenant {
  id: string;
  name: string;
  slug: string;
}

export interface User {
  id: string;
  email: string;
  first_name: string;
  last_name: string;
  role: string;
  avatar_url: string | null;
  tenants: Tenant[];
  permissions?: string[];
  is_system_admin?: boolean;
  field_permissions?: Record<string, any>;
}

export interface AuthState {
  user: User | null;
  currentTenant: Tenant | null; isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
  setUser: (user: User | null) => void;
  setTenant: (tenant: Tenant | null) => void;
  setAuthenticated: (authed: boolean) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  setPermissions: (perms: string[], isSystemAdmin: boolean, fieldPerms: Record<string, any>) => void;
  logout: () => void;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: null,
  currentTenant: null,
  isAuthenticated: false,
  isLoading: false,
  error: null,
  setUser: (user) =>
    set({
      user,
      isAuthenticated: !!user,
      currentTenant: user?.tenants?.[0] ?? null,
    }),
  setTenant: (tenant) => set({ currentTenant: tenant }),
  setAuthenticated: (authed) => set({ isAuthenticated: authed }),
  setLoading: (loading) => set({ isLoading: loading }),
  setError: (error) => set({ error }),
  setPermissions: (perms, isSystemAdmin, fieldPerms) =>
    set((state) => ({
      user: state.user
        ? {
            ...state.user,
            permissions: perms,
            is_system_admin: isSystemAdmin,
            field_permissions: fieldPerms,
          }
        : null,
    })),
  logout: () =>
    set({
      user: null,
      currentTenant: null,
      isAuthenticated: false,
      error: null,
    }),
}));
