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

interface AuthState {
  user: User | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  
  // Actions
  setUser: (user: User | null) => void;
  login: (email: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  checkSession: () => Promise<void>;
}

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

      setUser: (user) => set({ 
        user, 
        isAuthenticated: !!user,
        isLoading: false,
      }),

      login: async (email, password) => {
        set({ isLoading: true });
        try {
          await api.login(email, password);
          const session = await api.getSession();
          if (session?.user) {
            set({ 
              user: session.user, 
              isAuthenticated: true,
              isLoading: false,
            });
          } else {
            throw new Error('Failed to get session');
          }
        } catch (error) {
          set({ isLoading: false });
          throw error;
        }
      },

      logout: async () => {
        try {
          await api.logout();
        } finally {
          set({ user: null, isAuthenticated: false });
        }
      },

      checkSession: async () => {
        set({ isLoading: true });
        try {
          const session = await api.getSession();
          if (session?.user) {
            set({ 
              user: session.user, 
              isAuthenticated: true,
              isLoading: false,
            });
          } else {
            set({ 
              user: null, 
              isAuthenticated: false,
              isLoading: false,
            });
          }
        } catch {
          set({ 
            user: null, 
            isAuthenticated: false,
            isLoading: false,
          });
        }
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({ user: state.user }),
    }
  )
);
