import apiClient from "@/lib/api/client";
import type { RegistrationsDownload } from "@/lib/api/types";
import type { ApiResponse, QueryParams } from "@/lib/api/types";
import type { RegistrationResponseRecord } from "@/features/opportunities/payment";
import type { LearnServeRegistrationRecord } from "@/features/opportunities/permissionRecord";
import type {
  LearnServeOpportunityCardRecord,
  LearnServeOpportunityDetailRecord,
} from "@/features/opportunities/opportunityRecord";

/* `index()` answers with the website/card resource, `show()` with the detail
   one — they are not the same shape. See `opportunityRecord.ts`. */
export const getLearnServeOpportunitiesList = (
  params?: QueryParams
): Promise<ApiResponse<LearnServeOpportunityCardRecord[]>> =>
  apiClient.get("/learn-serve-opportunities/", { params }).then((r) => r.data);

export const getLearnServeOpportunityById = (
  id: string
): Promise<ApiResponse<LearnServeOpportunityDetailRecord>> =>
  apiClient.get(`/learn-serve-opportunities/${id}/`).then((r) => r.data);

/* Both writes answer with the **detail** resource. */
export const createLearnServeOpportunity = (
  /* `FormData` — multipart in every call, same as the volunteering form. The
     field-level contract is typed at `buildLearnServePayload`'s input. */
  data: FormData
): Promise<ApiResponse<LearnServeOpportunityDetailRecord>> =>
  apiClient.post("/learn-serve-opportunities/", data).then((r) => r.data);

/**
 * See `updateVolunteerOpportunity` — same PATCH+multipart workaround.
 *
 * The route is `Route::match(['put','patch'], 'learn-serve-opportunities/{id}/')`:
 * there is **no POST**. This only works because Laravel reads `_method` out of
 * a multipart body, so the payload has to be `FormData` — a plain object would
 * post to a route that does not accept POST and come back 405 with nothing
 * saved. The parameter type says so rather than the call guessing at runtime.
 */
export const updateLearnServeOpportunity = ({
  id,
  data,
}: {
  id: string;
  data: FormData;
}): Promise<ApiResponse<LearnServeOpportunityDetailRecord>> => {
  data.append("_method", "PATCH");
  return apiClient.post(`/learn-serve-opportunities/${id}/`, data).then((r) => r.data);
};

/*
 * POST, not PATCH, even though the route is `match(['post', 'patch'])` and the
 * operation is a partial update: PHP only parses a multipart body for POST, so
 * on a PATCH it populates neither `$_POST` nor `$_FILES` and Laravel sees an
 * empty request — the images never arrive. (Symfony re-reads `php://input` for
 * PATCH only when the type is x-www-form-urlencoded, never multipart.) The
 * volunteer twin, `updateVolunteerOpportunityImages`, has always used POST for
 * the same call; this one had drifted.
 *
 * `updateOpportunityImages()` stores every `opportunity_images_*` /
 * `new_opportunity_images_*` file with `is_after_completed: true` — this is the
 * **after-completion gallery** endpoint, not a general image update. It also
 * calls `MediaKeepSet::validate()` and then **discards the result** without
 * calling `apply()`, so an `existing_image_ids` sent here is checked for
 * ownership and then ignored: nothing is deleted. Removal goes through
 * `deleteOpportunityImage`.
 *
 * The reply is the whole opportunity in the detail shape.
 */
export const updateLearnServeOpportunityImages = ({
  id,
  formData,
}: {
  id: string;
  formData: FormData;
}): Promise<ApiResponse<LearnServeOpportunityDetailRecord>> =>
  apiClient.post(`/learn-serve-opportunities/${id}/update_images/`, formData).then((r) => r.data);

export interface LearnServeRegistrationPayload {
  opportunity_id: string | number;
  time_slot_id?: number;
  /** Resubmit after a 409 schedule conflict: cancel the clashing registration first. */
  cancel_conflicting?: boolean;
}

/**
 * 201 with the created registration, through the **same**
 * `LearnServeOpportunityRegistrationResource` the organizer's list returns —
 * so it is the same record type, not a reduced one.
 *
 * **Except on a paid opportunity (BE-125)**, where the same endpoint answers a
 * different shape: `{ registration, transaction }`, with the message
 * «complete payment to confirm your spot». The branch is the server's
 * (`$opportunity->is_paid`), so the caller reads the reply rather than
 * predicting it — see `features/opportunities/payment.ts`, which is also where
 * the one-shot nature of `transaction.gateway_checkout_url` is written down.
 *
 * The caller still checks `isApiSuccess()` rather than trusting the HTTP
 * status alone. Re-verified on 2026-10-04: **no** controller in this API
 * passes 200 to `ApiResponse::error`/`fail` any more, so today every refusal
 * really does arrive as a non-2xx and lands in `catch`. The envelope check is
 * kept because it costs nothing and the envelope is the contract — a 200 with
 * `key: "fail"` would otherwise be reported to the reader as a success.
 */
export const registerForLearnServeOpportunity = (
  data: LearnServeRegistrationPayload
): Promise<ApiResponse<RegistrationResponseRecord>> =>
  apiClient.post("/learn-serve-opportunity-registrations/", data).then((r) => r.data);

/** `data: null` — the outcome is the `msg`. */
export const unregisterFromLearnServeOpportunity = (
  id: string
): Promise<ApiResponse<null>> =>
  apiClient.post(`/learn-serve-opportunities/${id}/unregister/`).then((r) => r.data);

/*
 * BE-122 — `closeLearnServeOpportunityRegistration` and
 * `reopenLearnServeOpportunityRegistration` were removed from here, because
 * the two routes behind them were removed from the API. Registration on a
 * development opportunity now closes on its own: at the end of its `due_date`,
 * 3 hours before the start when it has none, or once it is full, driven by
 * the backend's hourly `fursa:close-learn-serve-registration` command.
 *
 * The state is still readable — `is_registration_closed` /
 * `is_registration_open` on the detail payload — and `LearnServeActionRail`
 * still shows it. Nothing offers to change it.
 *
 * Volunteering keeps both halves (`services/registrations.ts`), and an event
 * keeps its single toggling `close-registration/`.
 */

/**
 * The organizer removing one registrant — which **rejects** rather than
 * deletes, exactly like the volunteering side: the row's status becomes
 * `rejected` and the registrant is notified. The reply echoes the pair it
 * acted on.
 */
export const deleteLearnServeRegistrationByOpportunity = ({
  opportunity_id,
  user_id,
  confirm = false,
}: {
  opportunity_id: string | number;
  user_id: string | number;
  /**
   * BE-138 — a participant who attended or holds a certificate is refused
   * (422) unless this is set. The organizer's own confirmation dialog is that
   * opt-in, so the screen sends it; their record stays archived either way.
   */
  confirm?: boolean;
}): Promise<ApiResponse<{ user_id: number; status: string }>> =>
  apiClient
    .delete(`/learnserve/${opportunity_id}/unregister/${user_id}/`, {
      params: confirm ? { confirm: 1 } : undefined,
    })
    .then((r) => r.data);

export const getLearnServeRegistrations = ({
  opportunity_id,
  ...params
}: {
  opportunity_id: string;
} & QueryParams): Promise<ApiResponse<LearnServeRegistrationRecord[]>> =>
  apiClient.get(`/learn-serve-opportunities/${opportunity_id}/registrations/`, { params }).then((r) => r.data);

export const downloadLearnServeRegistrations = ({
  opportunity_id,
  search,
  attended,
  all_data,
}: {
  opportunity_id: string;
  search?: string;
  attended?: boolean;
  all_data?: boolean;
}): Promise<RegistrationsDownload> => {
  const params = new URLSearchParams();
  params.append("download", "true");
  if (search) params.append("search", search);
  if (attended !== undefined) params.append("attended", String(attended));
  if (all_data) params.append("all_data", "true");

  return apiClient
    .get(`/learn-serve-opportunities/${opportunity_id}/registrations/`, {
      params,
    })
    .then((r) => r.data.data);
};

/**
 * `LearnServeRegistrationController::updateAttendance()`.
 *
 * `is_attended` is the only `required` key — it marks *or unmarks*, so `false`
 * is a real value and not an omission.
 *
 * The other two are `nullable` in the validator and then constrained by the
 * controller: without `mark_all` an empty `registration_ids` is a 400
 * ("registration_ids is required unless mark_all is true."). A union says it
 * once. Sending both is accepted, with `mark_all` winning — the id filter is
 * simply not applied — which is why `registration_ids` is `never` on that
 * branch rather than optional.
 *
 * Also refused, as a 400 rather than a validation error: any call after the
 * preparation deadline (`preparationValidUntil()`), and `is_attended: true`
 * before the final-day scan opens. On a paid course only seat holders are
 * marked. `skipped_unpaid_count` is NOT the number of skipped rows in the
 * selection: the server counts every unpaid registration of the course before
 * it applies `registration_ids` (`LearnServeRegistrationController.php:853-863`
 * at `3fe127d`). Use `skippedFromSelection()` instead.
 */
export type UpdateLearnServeAttendanceBody = {
  is_attended: boolean;
} & (
  | { registration_ids: number[]; mark_all?: never }
  | { mark_all: true; registration_ids?: never }
);

export const updateLearnServeAttendance = ({
  opportunity_id,
  data,
}: {
  opportunity_id: string;
  data: UpdateLearnServeAttendanceBody;
}): Promise<ApiResponse<{ updated_count: number; skipped_unpaid_count?: number }>> =>
  apiClient.patch(`/learn-serve-opportunities/${opportunity_id}/update-attendance/`, data).then((r) => r.data);

/**
 * How many of the rows the organizer selected the server did not mark (unpaid
 * on a paid course): the selection minus the server's `updated_count`, which
 * is computed after the selection filter. Never negative; 0 when the server
 * sent no count.
 */
export const skippedFromSelection = (selected: number, updatedCount: unknown): number => {
  const updated = Number(updatedCount);
  return Number.isFinite(updated) ? Math.max(0, selected - updated) : 0;
};

/**
 * `GET /learn-serve-opportunities/{id}/registration/payment/` —
 * `PaymentStatusResource`: the viewer's own payment and, once one exists, its
 * refund. Read on a cancelled course to tell «الاسترجاع قيد المعالجة» from a
 * finished refund (client answers p.2, item 9); the detail's own
 * `payment_status` turns "refunded" as soon as a refund-all holds the course,
 * before the money is back.
 */
export interface LearnServePaymentStatusRecord {
  registration_id: number | null;
  opportunity_id: number | null;
  payment_status: string | null;
  gross_amount: string | number | null;
  currency: string | null;
  paid_at: string | null;
  /** Backend `bf3140b`: whether the same checkout can still be finished, and its link while it can. */
  resumable?: boolean;
  gateway_checkout_url?: string | null;
  checkout_expires_at?: string | null;
  /** Why an attempt ended (`PaymentNotices`), with the message in the request language. */
  outcome?: string | null;
  outcome_message?: string | null;
  refund: {
    status: "pending" | "processing" | "succeeded" | "declined" | "failed" | string;
    refund_amount: string | number | null;
    deduction_amount: string | number | null;
    refunded_at: string | null;
  } | null;
}

export const getLearnServePaymentStatus = (
  opportunityId: string
): Promise<ApiResponse<LearnServePaymentStatusRecord>> =>
  apiClient.get(`/learn-serve-opportunities/${opportunityId}/registration/payment/`).then((r) => r.data);

/**
 * `POST /payments/{reference}/verify/` — the Upay return page asks the API for
 * the real state of the payer's own attempt (Upay's `requested_order_id` is the
 * reference). Answers the same `PaymentStatusResource`; 404 for anyone else's.
 * Throttled to 12 a minute.
 */
export const verifyPayment = (
  reference: string
): Promise<ApiResponse<LearnServePaymentStatusRecord>> =>
  apiClient.post(`/payments/${encodeURIComponent(reference)}/verify/`).then((r) => r.data);
