/**
 * Event API Client
 * Handles event-related API requests
 */

import type { Event } from "@mosaic/shared";
import { apiGet, type ApiResponse } from "./client";

export interface EventFilters {
  /** Filter events starting from this date (inclusive) */
  startFrom?: Date;
  /** Filter events starting up to this date (inclusive) */
  startTo?: Date;
  /** Filter by project ID */
  projectId?: string;
  /** Filter by all-day events */
  allDay?: boolean;
  /** Page number (1-based) */
  page?: number;
  /** Items per page (max 100) */
  limit?: number;
}

/**
 * Fetch events with optional filters
 *
 * @param workspaceId - Workspace ID sent via X-Workspace-Id header
 * @param filters - Optional query parameter filters
 */
export async function fetchEvents(workspaceId?: string, filters?: EventFilters): Promise<Event[]> {
  const params = new URLSearchParams();

  if (filters?.startFrom) {
    params.append("startFrom", filters.startFrom.toISOString());
  }
  if (filters?.startTo) {
    params.append("startTo", filters.startTo.toISOString());
  }
  if (filters?.projectId) {
    params.append("projectId", filters.projectId);
  }
  if (filters?.allDay !== undefined) {
    params.append("allDay", String(filters.allDay));
  }
  if (filters?.page !== undefined) {
    params.append("page", String(filters.page));
  }
  if (filters?.limit !== undefined) {
    params.append("limit", String(filters.limit));
  }

  const queryString = params.toString();
  const endpoint = queryString ? `/api/events?${queryString}` : "/api/events";

  const response = await apiGet<ApiResponse<Event[]>>(endpoint, workspaceId);
  return response.data;
}
