import { create } from 'zustand';
import * as authService from '../services/authService';

const useAuthStore = create((set) => ({
  session: null,
  user: null,
  loading: false,
  error: null,

  setSession: (session) =>
    set({
      session,
      user: session?.user ?? null,
      loading: false,
      error: null,
    }),

  login: async (email, password) => {
    set({ loading: true, error: null });
    try {
      const data = await authService.signIn(email, password);
      set({ session: data.session, user: data.user, loading: false });
      return data;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  loginAsDemo: async () => {
    set({ loading: true, error: null });
    try {
      const data = await authService.signInAsDemo();
      set({ session: data.session, user: data.user, loading: false });
      return data;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  loginWithGoogle: async () => {
    set({ loading: true, error: null });
    try {
      const data = await authService.signInWithGoogle();
      set({ loading: false });
      return data;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  register: async (email, password) => {
    set({ loading: true, error: null });
    try {
      const data = await authService.signUp(email, password);
      // If signup returned a session (offline mode or auto-confirm), set it
      if (data?.session) {
        set({
          session: data.session,
          user: data.session?.user ?? data.user ?? null,
          loading: false,
        });
      } else {
        set({ loading: false });
      }
      return data;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  logout: async () => {
    try {
      await authService.signOut();
    } catch (_) {
      // proceed even if signOut fails (e.g. network)
    }
    set({ session: null, user: null, error: null });
  },

  fetchSession: async () => {
    try {
      const session = await authService.getSession();
      set({ session, user: session?.user ?? null });
      return session;
    } catch (_) {
      set({ session: null, user: null });
      return null;
    }
  },

  clearError: () => set({ error: null }),
}));

export default useAuthStore;
