import { test } from "node:test";
import assert from "node:assert/strict";
import { includeHeldGeneralTag, normalizeInterests, resolveInterestOptionIds } from "@/lib/interests";
import { paymentReferenceFromQuery, paymentReturnState, shouldPollPayment, resumableCheckoutUrl } from "@/features/opportunities/paymentReturn";
import { certificatesNeedSending, certificatesOutdatedNote } from "@/features/opportunities/certificatesOutdated";
import type { LearnServePaymentStatusRecord } from "@/features/opportunities/services/learnServe";
import { metadataText } from "@/lib/i18n/metadataCopy";
import { metaTitle, metaDescription } from "@/features/shared/services/detailMetadata";

test("A13: editing an old General-only record retains its required tag after choices load", () => {
  const held = [{ id: 41, name_ar: "عام", name_en: "General" }];
  const options = includeHeldGeneralTag([{ id: "7", label: "الصحة" }], held, "ar");
  assert.deepEqual(options, [{ id: "7", label: "الصحة" }, { id: "41", label: "عام" }]);
  assert.deepEqual(resolveInterestOptionIds(normalizeInterests(null, held), options), ["41"]);
});

test("A13: fallback is not offered on new forms; other retired values are not restored", () => {
  assert.deepEqual(includeHeldGeneralTag([], undefined, "ar"), []);
  assert.deepEqual(includeHeldGeneralTag([], [{ id: 9, name_en: "Retired" }], "en"), []);
  assert.deepEqual(includeHeldGeneralTag([{ id: "41", label: "General" }], [{ id: 41, name_en: "General" }], "en"), [{ id: "41", label: "General" }]);
});

const payment = (extra: Partial<LearnServePaymentStatusRecord>): LearnServePaymentStatusRecord => ({
  registration_id: 1, opportunity_id: 2, payment_status: "pending", gross_amount: "20.000", currency: "KWD", paid_at: null, refund: null, ...extra,
});

test("payment return ignores the redirect result and validates the reference", () => {
  assert.equal(paymentReferenceFromQuery(new URLSearchParams("result=CAPTURED")), null);
  assert.equal(paymentReferenceFromQuery(new URLSearchParams("requested_order_id=FRS-123&result=FAILED")), "FRS-123");
  assert.equal(paymentReferenceFromQuery(new URLSearchParams("requested_order_id=../../other")), null);
});

test("late captures waiting for a refund must never be shown as a successful booking", () => {
  const refund = { status: "processing", refund_amount: "20.000", deduction_amount: "0.000", refunded_at: null };
  assert.equal(paymentReturnState(payment({ payment_status: "paid", refund })), "refunding");
  assert.equal(paymentReturnState(payment({ payment_status: "paid", refund: { ...refund, status: "failed" } })), "refunding");
  assert.equal(paymentReturnState(payment({ payment_status: "refunded", refund: { ...refund, status: "succeeded" } })), "refunded");
});

test("payment polling stops at the budget and never polls a settled booking", () => {
  assert.equal(shouldPollPayment("pending", 9), true);
  assert.equal(shouldPollPayment("pending", 10), false);
  assert.equal(shouldPollPayment("paid", 0), false);
  assert.equal(resumableCheckoutUrl(payment({ resumable: false, gateway_checkout_url: "https://pay.example/checkout" })), null);
  assert.equal(resumableCheckoutUrl(payment({ resumable: true, gateway_checkout_url: "javascript:alert(1)" })), null);
});

test("A15: an up-to-date certificate disables sending and hides stale notes", () => {
  assert.equal(certificatesNeedSending({ certificates_outdated: false }), false);
  assert.equal(certificatesOutdatedNote({ certificates_outdated: false, certificates_outdated_note_ar: "قديم" }, "ar"), null);
  assert.equal(certificatesNeedSending({ certificates_outdated: true }), true);
  assert.equal(certificatesOutdatedNote({ certificates_outdated: true, certificates_outdated_note_ar: "تم التعديل", certificates_outdated_note_en: "Changed" }, "ar"), "تم التعديل");
});

test("metadata follows the chosen language and preserves administrator-written titles", () => {
  assert.equal(metadataText("Opportunities", "ar"), "الفرص");
  assert.equal(metadataText("Opportunities", "en"), "Opportunities");
  assert.equal(metadataText("اسم خاص من الإدارة", "ar"), "اسم خاص من الإدارة");
  assert.equal(metadataText("%s | Fursa", "ar"), "%s | فرصة");
});

test("public record metadata chooses Arabic after the shared cache read, with an English fallback", () => {
  const record = { title_ar: "الفعالية", title_en: "Event", description_ar: "<p>تفاصيل المشاركة</p>", description_en: "<p>Details</p>" };
  assert.equal(metaTitle(record, "Fallback", "ar"), "الفعالية");
  assert.equal(metaDescription(record, "Fallback", "ar"), "تفاصيل المشاركة");
  assert.equal(metaTitle(record, "Fallback", "en"), "Event");
  assert.equal(metaTitle({ title_en: "Only available copy" }, "Fallback", "ar"), "Only available copy");
});
