import { fetchApi, fetchBlob } from './client';
import type {
  DashboardData,
  AnalyticsData,
  ExportedTicket,
  ExportedPayment,
  FinancialSummary,
} from './types';

export const adminApi = {
  getDashboard: () => fetchApi<{ dashboard: DashboardData }>('/api/admin/dashboard'),
  getAnalytics: () => fetchApi<{ analytics: AnalyticsData }>('/api/admin/analytics'),
  exportTickets: (eventId?: string) => {
    const query = eventId ? `?eventId=${eventId}` : '';
    return fetchApi<{ tickets: ExportedTicket[] }>(`/api/admin/export/tickets${query}`);
  },
  exportFinancial: (params?: { startDate?: string; endDate?: string; eventId?: string }) => {
    const query = new URLSearchParams();
    if (params?.startDate) query.set('startDate', params.startDate);
    if (params?.endDate) query.set('endDate', params.endDate);
    if (params?.eventId) query.set('eventId', params.eventId);
    return fetchApi<{ payments: ExportedPayment[]; summary: FinancialSummary }>(`/api/admin/export/financial?${query}`);
  },
  /** Download attendee export as a file (CSV). Returns a Blob. */
  exportAttendees: (eventId: string, params?: { status?: string; format?: string; q?: string }) => {
    const query = new URLSearchParams();
    if (params?.status) query.set('status', params.status);
    if (params?.format) query.set('format', params.format);
    if (params?.q) query.set('q', params.q);
    return fetchBlob(
      `/api/admin/events/${eventId}/attendees/export?${query}`,
      `attendees-${new Date().toISOString().split('T')[0]}.csv`
    );
  },
  /** Download tickets export as CSV. Returns a Blob. */
  exportTicketsCSV: (eventId: string, params?: { status?: string; q?: string }) => {
    const query = new URLSearchParams();
    if (params?.status) query.set('status', params.status);
    if (params?.q) query.set('q', params.q);
    return fetchBlob(
      `/api/admin/events/${eventId}/tickets/export?${query}`,
      `tickets-${new Date().toISOString().split('T')[0]}.csv`
    );
  },
};
