import type { LearnServePaymentStatusRecord } from "./services/learnServe";

/**
 * What a participant of a cancelled paid course sees under «ملغاة» (client
 * answers p.2, item 9): «الاسترجاع قيد المعالجة» until their own amount is
 * back, then that it was refunded. Read from the payment-status endpoint,
 * whose `payment_status` only becomes "refunded" when the refund succeeded.
 */
export type CancelledCourseRefundState = "processing" | "refunded" | null;

export function cancelledCourseRefundState(
  record: LearnServePaymentStatusRecord | null | undefined
): CancelledCourseRefundState {
  if (!record) return null;
  if (record.refund?.status === "succeeded" || record.payment_status === "refunded") return "refunded";
  if (record.payment_status === "paid" || record.refund) return "processing";
  return null;
}

/**
 * The detail's own `refund_status` (backend `bf3140b`). A failed refund is
 * retried by the administration, so the participant still reads «قيد
 * المعالجة». `undefined` means an older API: ask the payment endpoint instead.
 */
export function refundStateFromDetail(
  refundStatus: string | null | undefined
): CancelledCourseRefundState | undefined {
  if (refundStatus === undefined) return undefined;
  if (refundStatus === "refunded") return "refunded";
  return refundStatus === "processing" || refundStatus === "failed" ? "processing" : null;
}

/** Only a participant who may have paid asks: a paid course that is cancelled. */
export function shouldReadCancelledCourseRefund(data: {
  is_paid?: boolean | null;
  is_registered?: boolean;
  opportunity_status?: string;
  payment_status?: string | null;
} | null | undefined, isCreator: boolean): boolean {
  if (!data || isCreator || data.is_paid !== true) return false;
  if (data.opportunity_status !== "cancelled") return false;
  return data.is_registered === true || data.payment_status === "paid" || data.payment_status === "refunded";
}

/**
 * The publisher's own line for their refund-all request (A9: the course leaves
 * the public lists at once and stays with the administration until every
 * refund is done). Only «تم» on `completed`; a rejected request is announced
 * by notification and the course is listed again, so nothing is shown for it.
 */
export function publisherRefundAllKey(
  data: { refund_all_status?: string | null } | null | undefined,
  isCreator: boolean
): string | null {
  if (!isCreator) return null;
  switch (data?.refund_all_status) {
    case "pending": return "COMMON.REFUND_ALL_PENDING";
    case "processing": return "COMMON.REFUND_IN_PROGRESS";
    case "completed": return "COMMON.REFUND_ALL_COMPLETED";
    default: return null;
  }
}
