import { create } from 'zustand';
import { api, ApiError } from '../api/client';
import type { SessionUser } from '../api/types';

interface AuthState {
  user: SessionUser | null;
  loading: boolean;
  loginError: string | null;
  init: () => Promise<void>;
  loginWithGoogle: (credential: string) => Promise<void>;
  logout: () => Promise<void>;
}

const useAuthStore = create<AuthState>((set) => ({
  user: null,
  loading: true,
  loginError: null,

  init: async () => {
    try {
      const res = await api.get<{ user: SessionUser }>('/auth/me');
      set({ user: res.user, loading: false });
    } catch {
      set({ user: null, loading: false });
    }
  },

  loginWithGoogle: async (credential) => {
    set({ loginError: null });
    try {
      const res = await api.post<{ user: SessionUser }>('/auth/google', { credential });
      set({ user: res.user });
    } catch (err) {
      set({ loginError: err instanceof ApiError ? err.message : 'Přihlášení se nezdařilo' });
    }
  },

  logout: async () => {
    await api.post('/auth/logout');
    set({ user: null });
  },
}));

export default useAuthStore;
