import apiClient from "@/lib/api/client";
import type { ApiResponse, CountedApiResponse } from "@/lib/api/types";
import type { QueryParams } from "@/lib/api/types";
import type {
  OpportunityCardRecord,
  VolunteerOpportunityCardRecord,
  VolunteerOpportunityDetailRecord,
} from "@/features/opportunities/opportunityRecord";
import type { EventRecord } from "@/features/events/eventRecord";
import type { LicenseRequirement } from "@/features/opportunities/permissionRecord";

// ─── Opportunities ───────────────────────────────────────────────────────────

export const getOpportunitiesList = (
  params?: QueryParams
): Promise<ApiResponse<VolunteerOpportunityCardRecord[]>> =>
  apiClient.get("/list-volunteer-opportunities/", { params }).then((r) => r.data);

/**
 * A **mixed** list: volunteer cards, learn & serve cards *and* event cards,
 * flattened into one array and sorted by status.
 *
 * `listAllOpportunities()` merges three different resources, so a row is one
 * of three shapes. Discriminate before reading: the two opportunity shapes
 * carry `opportunity_type`, an event row carries `event_status` and no
 * `opportunity_type` at all — which is exactly the key the controller's own
 * sort falls back on.
 *
 * Two envelope details: `counts` sits at the **top level**, not under `meta`
 * (hence `CountedApiResponse`), and `meta.pagination` is present **only when
 * the caller passes `page` or `limit`** — without either, the whole list comes
 * back unpaginated.
 */
export const getAllOpportunities = (
  params?: QueryParams
): Promise<CountedApiResponse<Array<OpportunityCardRecord | EventRecord>>> =>
  apiClient.get("/list-all-opportunities/", { params }).then((r) => r.data);

/** Volunteer and learn & serve only — no events in this one. */
export const getUserOpportunities = (
  params?: QueryParams
): Promise<CountedApiResponse<OpportunityCardRecord[]>> =>
  apiClient.get("/list-user-opportunities/", { params }).then((r) => r.data);

/*
 * `pass_token` is **not read anywhere in the backend**.
 *
 * Grepping the whole of `fursa_backend/app` for it finds exactly one hit: the
 * allow-list in `RejectsUnknownWriteKeys`, which applies to writes only. Both
 * controllers below authorize from `$request->user()`, which the axios
 * interceptor already populates by attaching `Authorization: Token …` whenever
 * `authStore` holds one — so the creator-only fields arrive for a signed-in
 * reader with or without this parameter.
 *
 * The parameter and the `passToken` / second-argument plumbing that feeds it are
 * therefore inert. Kept rather than removed: the three call sites pass
 * `Boolean(authToken)`, which documents *intent* ("this read is authenticated")
 * at the point of use, and deleting the flag would quietly change three
 * signatures for no behavioural gain. Recorded so nobody adds a fourth
 * believing it does something.
 */
export const getOpportunityById = (
  id: string,
  passToken?: boolean
): Promise<ApiResponse<VolunteerOpportunityDetailRecord>> =>
  apiClient.get(`/opportunities/${id}/details/`, { params: passToken ? { pass_token: true } : {} }).then((r) => r.data);

/* `store()` and `update()` both answer with the **detail** resource, so the
   created or updated record comes back in the same shape `show()` returns. */
export const createVolunteerOpportunity = (
  /* `FormData`, not a `FormData | Record` union: this endpoint is multipart in every call
     — the licence image and the gallery ride along with the fields — and
     `buildVolunteerPayload` is the one thing that constructs it. Narrowing to
     `FormData` removes the plain-object half of the old union, which no caller
     used and which would have been silently serialised as JSON with the files
     dropped. The keys themselves are typed at the builder's input
     (`VolunteerFormValues`). */
  data: FormData
): Promise<ApiResponse<VolunteerOpportunityDetailRecord>> =>
  apiClient.post("/volunteer-opportunities/", data).then((r) => r.data);

// Plain POST, not PATCH: PHP never populates $_FILES on a literal PATCH body,
// so a multipart image update silently dropped the file server-side (same fix
// as `updateAccountInfo`). The route still accepts PUT/PATCH for JSON callers —
// `Route::match(['post','put','patch'], 'volunteer-opportunities/{id}/')` — but
// every call from here carries multipart, so POST is the only safe verb.
export const updateVolunteerOpportunity = ({
  id,
  data,
}: {
  id: string;
  /* Multipart, as above — which is also why the verb is POST. */
  data: FormData;
}): Promise<ApiResponse<VolunteerOpportunityDetailRecord>> =>
  apiClient.post(`/volunteer-opportunities/${id}/`, data).then((r) => r.data);

/**
 * Same PATCH/PUT removal as `updateVolunteerOpportunity` above.
 *
 * And the same thing to know as its learn-serve twin: this is the
 * **after-completion gallery** endpoint. `updateOpportunityImages()` stores
 * every file it finds with `is_after_completed: true`, and it validates an
 * `existing_image_ids` without ever applying it, so nothing is deleted here —
 * removal is `deleteOpportunityImage`.
 */
export const updateVolunteerOpportunityImages = ({
  id,
  formData,
}: {
  id: string;
  formData: FormData;
}): Promise<ApiResponse<VolunteerOpportunityDetailRecord>> =>
  apiClient.post(`/volunteer-opportunities/${id}/update_images/`, formData).then((r) => r.data);

type OpportunitySponsorType = "volunteer" | "learn-serve";

interface OpportunitySponsorRelation {
  id: string | number;
  organization?: { id?: string | number } | string | number | null;
}

const sponsorEndpoint = (type: OpportunitySponsorType, opportunityId: string) =>
  type === "volunteer"
    ? `/volunteer-opportunities/${opportunityId}/sponsors/`
    : `/learn-serve-opportunities/${opportunityId}/sponsors/`;

/**
 * Synchronize the sponsor picker through the dedicated relationship endpoints.
 * Sponsor row ids and organization ids are different, so removals must use the
 * relation id returned in `opportunity_sponsor_images[].id`.
 */
export const syncOpportunitySponsors = async ({
  type,
  opportunityId,
  organizationIds,
  currentSponsors = [],
}: {
  type: OpportunitySponsorType;
  opportunityId: string;
  organizationIds: string[];
  currentSponsors?: OpportunitySponsorRelation[];
}): Promise<void> => {
  const desiredIds = new Set(organizationIds.filter(Boolean).map(String));
  const currentByOrganization = new Map(
    currentSponsors.flatMap((sponsor) => {
      const organizationId =
        typeof sponsor.organization === "object" && sponsor.organization !== null
          ? sponsor.organization.id
          : sponsor.organization;
      return organizationId == null
        ? []
        : [[String(organizationId), String(sponsor.id)] as const];
    })
  );
  const endpoint = sponsorEndpoint(type, opportunityId);

  await Promise.all([
    ...Array.from(currentByOrganization.entries())
      .filter(([organizationId]) => !desiredIds.has(organizationId))
      .map(([, sponsorRelationId]) =>
        apiClient.delete(`${endpoint}${sponsorRelationId}/`)
      ),
    ...Array.from(desiredIds)
      .filter((organizationId) => !currentByOrganization.has(organizationId))
      .map((organizationId) =>
        apiClient.post(endpoint, { organization_id: Number(organizationId) })
      ),
  ]);
};

/**
 * Organizer-only: issue and email certificates for a completed volunteer
 * opportunity's attended registrations.
 *
 * Completion already issues certificates automatically, so this covers
 * attendance marked *after* that pass ran. It is idempotent — a second call
 * answers `certificates_sent: 0` when nothing new is eligible (BE-14). Learn &
 * serve has its own separate certificate pipeline; this route is only for
 * `volunteer_opportunity`.
 */
/** `certificates_sent` is 0 when there was nothing new to issue, which the
    `msg` also says — not an error. */
export const sendVolunteerOpportunityCertificates = (
  id: string
): Promise<ApiResponse<{ certificates_sent: number }>> =>
  apiClient
    .post<ApiResponse<{ certificates_sent: number }>>(
      `/volunteer-opportunities/${id}/certificates/send/`
    )
    .then((r) => r.data);

/**
 * BE-102 — the development-opportunity mirror of the call above, and the same
 * `{ certificates_sent }` reply. The route shipped on 2026-10-03; the path
 * below, trailing slash included, is the one registered.
 */
export const sendLearnServeOpportunityCertificates = (
  id: string
): Promise<ApiResponse<{ certificates_sent: number }>> =>
  apiClient
    .post<ApiResponse<{ certificates_sent: number }>>(
      `/learn-serve-opportunities/${id}/certificates/send/`
    )
    .then((r) => r.data);

/**
 * `OpportunityMediaController::deleteImages()`.
 *
 * **`type` is `in:volunteer,learnserve`** — one word, no hyphen. Worth a union
 * rather than a string, because the hyphenated spelling is real elsewhere:
 * `syncOpportunitySponsors` takes `"volunteer" | "learn-serve"`, and
 * `useLearnServeSubmit` calls both of them four lines apart with the two
 * different spellings. Both are currently correct; nothing but the type would
 * keep them that way.
 *
 * `image_ids` is `['required', 'array', 'min:1']`.
 */
export interface DeleteOpportunityImagesBody {
  /** At least one. */
  image_ids: number[];
  type: "volunteer" | "learnserve";
}

/**
 * Per-image outcomes, not a single verdict: the controller loops, skips an
 * image it cannot find or does not own with a reason, and reports both lists.
 * So a 200 does not mean every id was deleted.
 */
export interface DeleteOpportunityImagesResult {
  deleted_count?: number;
  errors?: Array<{ image_id: number; error: string }>;
}

export const deleteOpportunityImage = (
  data: DeleteOpportunityImagesBody
): Promise<ApiResponse<DeleteOpportunityImagesResult>> =>
  apiClient.delete("/delete-opportunity-image/", { data }).then((r) => r.data);

/**
 * Streams an uploaded opportunity/event image back as a file. Unlike the
 * registration "download" endpoints (which return a JSON `downloadUrl`), this
 * one returns the bytes, so the caller saves the blob itself.
 */
export const downloadOpportunityImage = ({
  image_id,
  fallbackName = "opportunity_image",
}: {
  image_id: number;
  fallbackName?: string;
}) =>
  apiClient
    .get("/download-url/", {
      params: { image_id },
      responseType: "blob",
    })
    .then((response) => {
      // Prefer the server-supplied filename when Content-Disposition carries one
      const disposition = response.headers["content-disposition"] as
        | string
        | undefined;
      const match = disposition?.match(/filename="(.+)"/);
      return {
        blob: response.data as Blob,
        filename: match?.[1] || `${fallbackName}_${Date.now()}.jpg`,
      };
    });

/**
 * `OpportunityDeletionController::requestDeletion()`.
 *
 * `data: null` — the outcome is the `msg`, and the two refusals matter more
 * than the payload: a 404 when the opportunity is not the caller's, and a
 * **400 when a request is already pending** ("A deletion request for this
 * opportunity is already pending."). Pressing the button twice is the second
 * one, so the caller has to show that message rather than treat it as a
 * generic failure.
 *
 * `type` is `in:volunteer,learnserve` — one word, as at
 * `deleteOpportunityImage`. `reason` is accepted and `nullable`; nothing sends
 * one yet.
 */
export const requestOpportunityDeletion = ({
  id, type, reason, requestOnly = false,
}: {
  id: string;
  type: "volunteer" | "learnserve";
  reason?: string;
  requestOnly?: boolean;
}): Promise<ApiResponse<null>> =>
  apiClient.post(`/opportunities/${id}/request-deletion/`, { type: type.toLowerCase(), reason, request_only: requestOnly }).then((r) => r.data);

// ─── Creator eligibility ─────────────────────────────────────────────────────

export const checkLicenseRequirement = (): Promise<
  ApiResponse<LicenseRequirement>
> => apiClient.get("/check-license-requirement/").then((r) => r.data);
