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

const TOKEN_KEY = 'fiberops_token';
const TENANT_KEY = 'fiberops_tenant';

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

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

  hydrate: async () => {
    try {
      const token = await SecureStore.getItemAsync(TOKEN_KEY);
      const tenantSlug = await SecureStore.getItemAsync(TENANT_KEY);
      if (token && tenantSlug) {
        const res = await api.get('/api/v1/auth/me');
        set({ token, tenantSlug, user: res.data, isLoading: false });
      } else {
        set({ isLoading: false });
      }
    } catch {
      await SecureStore.deleteItemAsync(TOKEN_KEY);
      await SecureStore.deleteItemAsync(TENANT_KEY);
      set({ token: null, tenantSlug: null, user: null, isLoading: false });
    }
  },

  login: async (tenantSlug, email, password) => {
    const res = await api.post('/api/v1/auth/login', { tenantSlug, email, password });
    const { accessToken, user } = res.data;
    await SecureStore.setItemAsync(TOKEN_KEY, accessToken);
    await SecureStore.setItemAsync(TENANT_KEY, tenantSlug);
    set({ token: accessToken, tenantSlug, user });
  },

  logout: async () => {
    await SecureStore.deleteItemAsync(TOKEN_KEY);
    await SecureStore.deleteItemAsync(TENANT_KEY);
    set({ token: null, tenantSlug: null, user: null });
  },
}));
