import moment from "moment";
import type { PaymentStatus } from "@/features/opportunities/payment";
import { hasOpportunityEnded, isOpportunityCancelled, type ReviewSchedule } from "@/features/shared/clientReviewPolicy";

/**
 * BE-125 — one row of the organizer's «المشاركون والمدفوعات» table
 * (`LearnServeParticipantPaymentResource`).
 *
 * Every money field is **nullable**, and that is not an oversight: the row is
 * a registration, and a registration on a paid opportunity exists before any
 * transaction does. A free opportunity's rows carry no transaction at all, so
 * they arrive with `payment_status: null` and every amount null.
 *
 * `gateway_fee_amount` and `net_amount` stay null until the gateway reports
 * them, which today is never — the Upay driver is a stub that returns a zero
 * fee, so `net_amount` is only filled once the real gateway lands.
 */
export interface ParticipantPaymentRecord {
  registration_id: number;
  user_id: number;
  user_name: string | null;
  user_email: string | null;
  /** The registration's own approval status, not the payment's. */
  status: string | null;
  payment_status: PaymentStatus | null;
  gross_amount: number | string | null;
  platform_fee_amount: number | string | null;
  gateway_fee_amount: number | string | null;
  net_amount: number | string | null;
  paid_at: string | null;
  refunded_at: string | null;
  /*
   * `can_refund` is still sent but is always false: a publisher never refunds
   * one participant (PDF p.18, `LearnServeParticipantPaymentResource`). Refunds
   * go through the refund-all request — see `canOpenRefundAll`.
   */
}

/**
 * Whether «طلب استرداد الكل» can be opened: someone has paid and the course has
 * neither ended nor been cancelled. A running course qualifies too (client
 * answer 9 «وحتى لو الدورة بدأت», user confirmation of 5 November; backend
 * `7fc047d`), with or without recorded attendance. The quote endpoint stays the
 * authority — it answers 409 `course_ended` or 422 `no_paid_participants`, and
 * the dialog shows that message.
 */
export function canOpenRefundAll(
  rows: ReadonlyArray<Pick<ParticipantPaymentRecord, "payment_status">>,
  schedule?: ReviewSchedule | null,
  now: moment.Moment = moment()
): boolean {
  if (!rows.some((row) => row.payment_status === "paid")) return false;
  return !isOpportunityCancelled(schedule) && !hasOpportunityEnded(schedule, now);
}

/**
 * The paging helpers key rows by `id`, and this resource names its key
 * `registration_id`. Mapped rather than aliased on the type, so the row that
 * reaches the table is the row the API sent plus one derived key.
 */
export interface ParticipantPaymentRow extends ParticipantPaymentRecord {
  id: number;
}

export const withRowId = (
  record: ParticipantPaymentRecord
): ParticipantPaymentRow => ({ ...record, id: record.registration_id });
