import { create } from 'zustand';
import * as SecureStore from 'expo-secure-store';

interface User {
  id: string;
  email: string;
  username: string;
  plan_tier: string;
  is_admin?: boolean;
}

interface AuthStore {
  user: User | null;
  token: string | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  setAuth: (user: User, token: string) => Promise<void>;
  logout: () => Promise<void>;
  initAuth: () => Promise<void>;
  isPremium: () => boolean;
  isAdvanced: () => boolean;
}

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

  setAuth: async (user, token) => {
    await SecureStore.setItemAsync('jwt', token);
    set({ user, token, isAuthenticated: true, isLoading: false });
  },

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

  initAuth: async () => {
    try {
      const token = await SecureStore.getItemAsync('jwt');
      if (token) {
        set({ token, isLoading: false });
      } else {
        set({ isLoading: false });
      }
    } catch (error) {
      set({ isLoading: false });
    }
  },

  isPremium: () => {
    const { user } = get();
    return user?.plan_tier === 'pro' || user?.plan_tier === 'premium';
  },

  isAdvanced: () => {
    const { user } = get();
    return user?.plan_tier === 'pro' || user?.plan_tier === 'premium';
  },
}));
