import { fetchApi } from './client';
import type { User } from './types';

export interface UsersListParams {
  role?: string;
  search?: string;
  accountStatus?: string;
  hasBookings?: 'yes' | 'no';
  registeredAfter?: string;
  registeredBefore?: string;
  eventId?: string;
  page?: number;
  pageSize?: number;
}

export const usersApi = {
  getAll: (params?: UsersListParams | string) => {
    // Back-compat: allow the old `getAll(role)` call shape.
    const p: UsersListParams = typeof params === 'string' ? { role: params } : params || {};
    const query = new URLSearchParams();
    if (p.role) query.set('role', p.role);
    if (p.search) query.set('search', p.search);
    if (p.accountStatus) query.set('accountStatus', p.accountStatus);
    if (p.hasBookings) query.set('hasBookings', p.hasBookings);
    if (p.registeredAfter) query.set('registeredAfter', p.registeredAfter);
    if (p.registeredBefore) query.set('registeredBefore', p.registeredBefore);
    if (p.eventId) query.set('eventId', p.eventId);
    if (p.page) query.set('page', String(p.page));
    if (p.pageSize) query.set('pageSize', String(p.pageSize));
    const qs = query.toString();
    return fetchApi<{ users: User[]; total: number; page: number; pageSize: number }>(`/api/users${qs ? `?${qs}` : ''}`);
  },

  getById: (id: string) => fetchApi<{ user: User }>(`/api/users/${id}`),

  update: (id: string, data: Partial<User>) =>
    fetchApi<{ user: User }>(`/api/users/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    }),

  delete: (id: string) =>
    fetchApi<{ message: string }>(`/api/users/${id}`, { method: 'DELETE' }),
};
