import apiClient from "@/lib/api/client";
import type { ApiResponse, QueryParams } from "@/lib/api/types";
import type { CalendarEntryRecord } from "@/features/calendar/calendarEntry";

/*
 * Not paginated: `index()` merges saved, registered and organized items into one
 * array and answers with `ApiResponse::success`, so there is no `meta`.
 */
export const getCalendar = (
  params?: QueryParams
): Promise<ApiResponse<CalendarEntryRecord[]>> =>
  apiClient.get("/my-calendar/", { params }).then((r) => r.data);

/**
 * iPadOS refuses to open a locally-generated blob in Calendar, so the .ics is
 * uploaded and the returned URL is opened instead.
 */
export interface UploadedIcsFile {
  /** The stored file's public URL, through `getimg()`. */
  file_url: string;
  /** The same URL with the scheme rewritten to `webcal://`. */
  webcal_url: string;
}

/**
 * The file key is **`ics_file`**, and the validation is strict about it: 1 MB
 * max, an `.ics` extension, and the contents must actually contain
 * `BEGIN:VCALENDAR` — a renamed file is rejected. 201 on success.
 */
export const uploadICSFile = (
  formData: FormData
): Promise<ApiResponse<UploadedIcsFile>> =>
  apiClient.post("/upload-ics/", formData).then((r) => r.data);

/**
 * `CalendarController::store()` — "exactly one of" the three references.
 *
 * All three keys are `nullable` in the validation, and the controller then
 * counts the non-empty ones and answers 400 unless there is exactly one, so a
 * union is the honest shape rather than three optional fields. The union does
 * not stop a caller passing `{}` cast from something wider, but it does stop
 * the two-reference body that the rule exists to refuse.
 *
 * `is_saved` is `nullable` and defaults to `true` server-side, both in the
 * `firstOrCreate` attributes and in the `update` that follows it.
 */
export type SaveToCalendarBody = (
  | { volunteer_opportunity_id: number }
  | { learn_serve_opportunity_id: number }
  | { event_id: number }
) & { is_saved?: boolean };

/**
 * The saved row, through `formatCalendarRow()` — the *same* shape as a
 * `GET /my-calendar/` row, which is why the record is reused rather than
 * redeclared. `calendar_id` is always present on this one: the controller
 * splices in the `my_calendars` id it just created.
 */
export const saveToCalendar = (
  data: SaveToCalendarBody
): Promise<ApiResponse<CalendarEntryRecord>> =>
  apiClient.post("/my-calendar/save/", data).then((r) => r.data);
