import assert from "node:assert/strict";
import { describe, test } from "node:test";
import moment from "moment";
import "moment/locale/ar";
import { clockTimeRange } from "@/features/shared/clockLabel";
import { opportunityStartsAt, opportunityEndsAt } from "@/features/shared/clientReviewPolicy";
import { canEditOrDelete, getOpportunityButtonState, isViewerOrganizer } from "@/features/shared/opportunityButtonState";
import { getCheckInWindow } from "@/features/opportunities/checkInWindow";
import { developmentScanOpensAt } from "@/features/opportunities/developmentAttendanceWindow";
import { isLiveScanWindow } from "@/features/opportunities/liveScanWindow";
import { nextProfileListingPage, profileListingRows } from "@/features/profile/profileListingPages";
import { buildLearnServeValidationSchema } from "@/features/opportunities/components/learnServeValidation";

describe("PDF pages 3/18/21: KWD paid authoring", () => {
  const schema = buildLearnServeValidationSchema({ developmentPaid: true, isLicenseRequired: false, modifiedOpportunityImages: [], internshipTypeId: "internship" });
  test("positive prices retain whole-fils precision", async () => {
    for (const price of ["0.001", "0.200", "20", "20.123", "0.500"]) await schema.validateAt("price", { is_paid: "true", learningType: "course", price });
  });
  test("non-finite, non-decimal, zero and sub-fils amounts are invalid", async () => {
    // ".500": backend `PlainPrice` (1983649) requires a leading digit.
    for (const price of ["", "Infinity", "1e3", "0x10", "0", "0.000", "-1", "0.0001", "20.1234", ".500"]) await assert.rejects(schema.validateAt("price", { is_paid: "true", learningType: "course", price }));
  });
  test("free and internship publishing does not require a hidden price", async () => {
    await schema.validateAt("price", { is_paid: "false", learningType: "course", price: "" });
    await schema.validateAt("price", { is_paid: "true", learningType: "internship", price: "" });
  });
});

describe("PDF pages 13/17/19: one schedule across lifecycle and attendance", () => {
  const schedule = {
    start_date: "2026-11-01", end_date: "2026-11-20", start_time: "08:00", end_time: "16:00",
    time_slots: [],
    timeslots_display: [
      { date: "2026-11-10", start_time: "22:00", end_time: "01:00" },
      { date: "2026-11-03", start_time: "10:00", end_time: "12:00" },
    ],
  };
  test("empty legacy slots do not mask scattered development sessions", () => {
    assert.equal(opportunityStartsAt(schedule)?.valueOf(), Date.parse("2026-11-03T10:00:00+03:00"));
    assert.equal(opportunityEndsAt(schedule)?.valueOf(), Date.parse("2026-11-11T01:00:00+03:00"));
    assert.equal(developmentScanOpensAt(schedule)?.valueOf(), Date.parse("2026-11-10T22:00:00+03:00"));
  });
  test("the same fallback schedule governs edit cutoff and preparation close", () => {
    assert.equal(canEditOrDelete(schedule, moment.parseZone("2026-11-02T10:00:00+03:00")), true);
    assert.equal(canEditOrDelete(schedule, moment.parseZone("2026-11-02T10:00:01+03:00")), false);
    assert.equal(getCheckInWindow(schedule, moment.parseZone("2026-11-14T01:00:00+03:00")).isClosed, true);
  });
  test("a date-only slot inherits the opportunity's daily times rather than midnight", () => {
    const item = { ...schedule, timeslots_display: [{ date: "2026-11-04" }] };
    assert.equal(opportunityStartsAt(item)?.valueOf(), Date.parse("2026-11-04T08:00:00+03:00"));
    assert.equal(opportunityEndsAt(item)?.valueOf(), Date.parse("2026-11-04T16:00:00+03:00"));
  });
  test("canonical instants outrank both stale action state and missing legacy dates", () => {
    const item = { start_at: "2026-11-03T10:00:00+03:00", end_at: "2026-11-03T12:00:00+03:00", action_state: "ended" };
    assert.equal(getOpportunityButtonState(item, moment.parseZone("2026-11-01T12:00:00+03:00")), "register");
    assert.equal(getOpportunityButtonState(item, moment.parseZone("2026-11-03T12:00:00+03:00")), "ended");
  });
  test("card ownership also recognizes the server's organizer relationship or flag", () => {
    assert.equal(isViewerOrganizer({ relationship_tags: ["organizer"] }, 8), true);
    assert.equal(isViewerOrganizer({ is_creator: true }, 8), true);
    assert.equal(isViewerOrganizer({ created_by: { id: "8" } }, 8), true);
    assert.equal(isViewerOrganizer({ relationship_tags: ["sponsor"], created_by: { id: 9 } }, 8), false);
  });
});

describe("PDF page 37: bilingual clock labels on every card", () => {
  const en = (key: string) => key === "COMMON.AM" ? "AM" : "PM";
  const ar = (key: string) => key === "COMMON.AM" ? "ص" : "م";
  test("global Arabic Moment locale cannot turn morning into afternoon", () => {
    const old = moment.locale();
    try {
      moment.locale("ar");
      assert.equal(clockTimeRange("09:00:00", "13:30", en), "09:00 AM - 01:30 PM");
      assert.equal(clockTimeRange("09:00", "13:30:00", ar), "09:00 ص - 01:30 م");
    } finally { moment.locale(old); }
  });
  test("noon and midnight have the correct meridiem", () => {
    assert.equal(clockTimeRange("00:00", "12:00", en), "12:00 AM - 12:00 PM");
  });
  test("optional and invalid clocks never produce Invalid date or a dangling separator", () => {
    assert.equal(clockTimeRange(null, "17:00", en), "05:00 PM");
    assert.equal(clockTimeRange("29:00", null, en), "");
    assert.equal(clockTimeRange("", "", en), "");
  });
});

describe("latest QR clarification: authoritative live scan windows", () => {
  const row = { opportunity_type: "learn_serve_opportunity" as const, scan_opens_at: "2026-11-04T16:30:00+03:00", scan_closes_at: "2026-11-05T00:00:00+03:00" };
  test("opens at session start, never an hour earlier", () => {
    assert.equal(isLiveScanWindow(row, Date.parse("2026-11-04T16:29:59+03:00")), false);
    assert.equal(isLiveScanWindow(row, Date.parse("2026-11-04T16:30:00+03:00")), true);
  });
  test("final midnight is excluded for development", () => {
    assert.equal(isLiveScanWindow(row, Date.parse("2026-11-04T23:59:59+03:00")), true);
    assert.equal(isLiveScanWindow(row, Date.parse("2026-11-05T00:00:00+03:00")), false);
  });
  test("offset-free legacy times use Kuwait rather than the browser zone", () => {
    assert.equal(isLiveScanWindow({ ...row, scan_opens_at: "2026-11-04 16:30:00", scan_closes_at: "2026-11-05 00:00:00" }, Date.parse("2026-11-04T13:30:00Z")), true);
  });
  test("missing, invalid and reversed windows do not offer a scan", () => {
    const now = Date.parse("2026-11-04T17:00:00+03:00");
    assert.equal(isLiveScanWindow({ ...row, scan_opens_at: "" }, now), false);
    assert.equal(isLiveScanWindow({ ...row, scan_closes_at: "invalid" }, now), false);
    assert.equal(isLiveScanWindow({ ...row, scan_opens_at: row.scan_closes_at, scan_closes_at: row.scan_opens_at }, now), false);
  });
  test("volunteering retains its separate API-provided early-arrival window", () => {
    assert.equal(isLiveScanWindow({ ...row, opportunity_type: "volunteer_opportunity", scan_opens_at: "2026-11-04T15:30:00+03:00" }, Date.parse("2026-11-04T15:30:00+03:00")), true);
  });
});

describe("PDF pages 12/25/37: complete profile listings", () => {
  test("more than 30 results remain reachable and terminate on the last page", () => {
    const data = Array.from({ length: 30 }, (_, id) => ({ id, opportunity_type: "volunteer_opportunity" }));
    const first = { data, meta: { pagination: { page: 1, limit: 30, total: 31, total_pages: 2 } } };
    const second = { data: [{ id: 30, opportunity_type: "volunteer_opportunity" }], meta: { pagination: { page: 2, limit: 30, total: 31, total_pages: 2 } } };
    assert.equal(nextProfileListingPage(first), 2);
    assert.equal(nextProfileListingPage(second), undefined);
    assert.equal(profileListingRows([first, second]).length, 31);
  });
  test("mixed products keep equal IDs while repeated rows do not duplicate", () => {
    const volunteer = { id: 8, opportunity_type: "volunteer_opportunity" };
    const development = { id: 8, opportunity_type: "learn_serve_opportunity" };
    const event = { id: 8 };
    assert.deepEqual(profileListingRows([{ data: [volunteer, development, event] }, { data: [volunteer] }]), [volunteer, development, event]);
  });
  test("empty or unpaginated responses do not produce an endless load-more action", () => {
    assert.equal(nextProfileListingPage({ data: [] }), undefined);
    assert.equal(nextProfileListingPage({ data: [{ id: 8 }] }), undefined);
    assert.equal(nextProfileListingPage({ data: [], meta: { pagination: { page: 1, limit: 30, total: 50, total_pages: 2 } } }), undefined);
  });
});
