import apiClient from "@/lib/api/client";
import type { ApiResponse } from "@/lib/api/types";

/** BE-194/195: server quotes are authoritative; the browser never executes refunds. */
export interface CancellationQuote {
  quote_id: string | null;
  /** `Kwd::format` strings ("20.000"); older payloads sent numbers. */
  gross_amount: number | string;
  deduction_amount: number | string;
  refund_amount: number | string;
  publisher_charge_amount: number | string;
  currency: "KWD";
  affected_participants: number;
  /** Refund-all quote only: the course is already running (backend `b1d70a4`). */
  started?: boolean;
  expires_at: string | null;
  can_request: boolean;
  /**
   * Participant: `CancellationRequest::websiteStatus()`. Publisher: a live quote
   * answers "available"; an existing refund-all request answers its own
   * `RefundAllRequest` status — pending, processing, completed (never
   * "rejected": a rejected request lets a new quote through).
   */
  status: "available" | "awaiting_trainer" | "pending" | "refunding" | "refund_failed" | "approved" | "rejected" | "processing" | "completed";
}

/**
 * The line the request dialog prints for a request that already exists, or
 * null when there is none. A refund-all is only «تم» once the server reports
 * `completed` (every paid participant refunded); `processing` means approved
 * with refunds still running, so nothing is announced as refunded before that.
 */
export function existingRequestStateKey(mode: CancellationMode, status: CancellationQuote["status"] | null | undefined): string | null {
  if (mode === "publisher") {
    if (status === "pending") return "COMMON.REFUND_ALL_PENDING";
    if (status === "processing") return "COMMON.REFUND_IN_PROGRESS";
    if (status === "completed") return "COMMON.REFUND_ALL_COMPLETED";
    return null;
  }
  if (status === "refunding" || status === "refund_failed") return "COMMON.REFUND_IN_PROGRESS";
  if (status === "awaiting_trainer" || status === "pending") return "COMMON.CANCELLATION_PENDING";
  return null;
}
export type CancellationMode = "participant" | "publisher";

/**
 * The cached reads a sent cancellation or refund-all request changes: the
 * detail (button «طلب الإلغاء قيد المراجعة» / «ملغاة»), the participant's own
 * payment state, and every list that shows the course — a refund-all hides it
 * from discovery at once and keeps it «ملغاة» in the owner's and participants'
 * own lists (A9). Marked stale rather than waiting out the 1-minute staleTime.
 */
const PAID_CANCELLATION_QUERY_ROOTS: ReadonlySet<string> = new Set([
  "learn-serve-opportunity",
  "learn-serve-opportunities",
  "learn-serve-payment-status",
  "opportunities-feed",
  "all-opportunities",
  "user-opportunities",
  "user-opportunities-counts",
]);

export function isAffectedByPaidCancellation(queryKey: readonly unknown[]): boolean {
  return typeof queryKey[0] === "string" && PAID_CANCELLATION_QUERY_ROOTS.has(queryKey[0]);
}
const base = (id: string, mode: CancellationMode) =>
  `/learn-serve-opportunities/${id}/${mode === "participant" ? "cancellation" : "refund-all"}`;
export const getCancellationQuote = (id: string, mode: CancellationMode): Promise<ApiResponse<CancellationQuote>> =>
  apiClient.get(`${base(id, mode)}-quote/`).then(r => r.data);
export const requestCancellation = (id: string, mode: CancellationMode, body: { quote_id: string; reason: string }): Promise<ApiResponse<{ status: CancellationQuote["status"] }>> =>
  apiClient.post(`${base(id, mode)}-requests/`, body).then(r => r.data);
