import { create } from 'zustand';
import * as SecureStore from 'expo-secure-store';
import { STORAGE_KEYS } from '../constants';

interface User {
  id: number;
  name: string;
  username: string;
  email: string;
  role: string;
  tenant_slug: string;
}

interface AuthState {
  token: string | null;
  user: User | null;
  tenantSlug: string | null;
  isLoading: boolean;
  isAuthenticated: boolean;

  setAuth: (token: string, user: User) => Promise<void>;
  setTenantSlug: (slug: string) => void;
  logout: () => Promise<void>;
  loadFromStorage: () => Promise<void>;
}

export const useAuthStore = create<AuthState>((set) => ({
  token: null,
  user: null,
  tenantSlug: null,
  isLoading: true,
  isAuthenticated: false,

  setAuth: async (token, user) => {
    await SecureStore.setItemAsync(STORAGE_KEYS.TOKEN, token);
    await SecureStore.setItemAsync(STORAGE_KEYS.USER, JSON.stringify(user));
    set({ token, user, isAuthenticated: true, tenantSlug: user.tenant_slug });
  },

  setTenantSlug: (slug) => {
    set({ tenantSlug: slug });
  },

  logout: async () => {
    await SecureStore.deleteItemAsync(STORAGE_KEYS.TOKEN);
    await SecureStore.deleteItemAsync(STORAGE_KEYS.USER);
    set({ token: null, user: null, isAuthenticated: false });
  },

  loadFromStorage: async () => {
    try {
      const token = await SecureStore.getItemAsync(STORAGE_KEYS.TOKEN);
      const userStr = await SecureStore.getItemAsync(STORAGE_KEYS.USER);
      if (token && userStr) {
        const user = JSON.parse(userStr) as User;
        set({ token, user, isAuthenticated: true, tenantSlug: user.tenant_slug, isLoading: false });
      } else {
        set({ isLoading: false });
      }
    } catch {
      set({ isLoading: false });
    }
  },
}));
