/**
 * Full audit, Development (remainder) — regression tests for F-DEV2-n.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { buildLearnServePayload } from "@/features/opportunities/components/buildLearnServePayload";
import type { LearnServeFormValues } from "@/features/opportunities/components/learnServeFormTypes";
import type { PublishPermissions } from "@/lib/publishPermissions";
import { usesSlotBooking } from "@/features/opportunities/components/learnServeRegistrationTarget";
import { isConsultationType } from "@/features/opportunities/components/learnServeDetailsTypes";
import { timeSlotItems } from "@/features/opportunities/services/registrations";
import { learnServeReadErrorAction } from "@/features/opportunities/components/learnServeReadError";

const permissions = {
  volunteer: true,
  development: true,
  internship: true,
  developmentPaid: true,
  developmentTypes: null,
} as unknown as PublishPermissions;

const values = (over: Partial<LearnServeFormValues> = {}): LearnServeFormValues =>
  ({
    title_ar: "عنوان", title_en: "", description_ar: "<p>وصف</p>", description_en: "",
    dueDate: "", startDate: "2027-02-01", endDate: "2027-02-05", startTime: "09:00", endTime: "12:00",
    age: [18, 30], participantsNeeded: "20", learningType: "course-id", learnServeFormat: "inperson-id",
    certificateType: "", gender: "gender-id", location: "", location_url: "", latitude: "", longitude: "",
    meetingLink: "", whatsappLink: "+965 5555 1234", is_paid: "false", price: "", opportunity_images: [],
    license_image: "", license_image_removed: false, _interests: [], sponsors: [{ sponsorId: "", position: 1 }],
    opportunity_nationality: "all", primary_language: "ar", ...over,
  }) as unknown as LearnServeFormValues;

const build = (over: Partial<LearnServeFormValues>) =>
  buildLearnServePayload({
    values: values(over), isUpdate: false, existingImageIds: [], publishPermissions: permissions,
    internshipTypeId: "internship-id", courseTypeId: "course-id", onlineFormatId: "online-id",
  }).formData;

describe("F-DEV2-1 «مساحة» registers like every other type unless it carries slots", () => {
  const space = { value_en: "Consultation", value_ar: "مساحة" };
  test("the type is still recognised", () => assert.equal(isConsultationType(space), true));
  test("no saved slots → ordinary confirmation, not an empty picker", () => {
    assert.equal(usesSlotBooking(isConsultationType(space), []), false);
    assert.equal(usesSlotBooking(isConsultationType(space), null), false);
    assert.equal(usesSlotBooking(isConsultationType(space), [{ date: null }]), false);
  });
  test("a legacy «مساحة» with dated slots keeps the picker", () => {
    assert.equal(usesSlotBooking(true, [{ date: "2027-02-01" }]), true);
  });
  test("other types never open the picker", () => {
    assert.equal(usesSlotBooking(isConsultationType({ value_en: "Course", value_ar: "دورة" }), [{ date: "2027-02-01" }]), false);
  });
});

describe("F-DEV2-2 GET /time-slots/ answers { items, remaining_participants }", () => {
  const slot = { id: 1, opportunity: 9, date: "2027-02-01", start_time: "09:00", end_time: "10:00" } as never;
  test("reads the items of the real envelope", () => {
    assert.deepEqual(timeSlotItems({ items: [slot], remaining_participants: 3 }), [slot]);
  });
  test("tolerates a bare array and a missing body", () => {
    assert.deepEqual(timeSlotItems([slot]), [slot]);
    assert.deepEqual(timeSlotItems(undefined), []);
    assert.deepEqual(timeSlotItems({} as never), []);
  });
});

describe("F-DEV2-3 links typed without a scheme are sent the way Laravel's `url` rule accepts", () => {
  test("in-person location link gains https://", () => {
    assert.equal(build({ location_url: "maps.google.com/x" }).get("location_url"), "https://maps.google.com/x");
  });
  test("online meeting link gains https://, an explicit scheme is kept", () => {
    assert.equal(build({ learnServeFormat: "online-id", meetingLink: "www.zoom.us/j/1" }).get("link"), "https://www.zoom.us/j/1");
    assert.equal(build({ learnServeFormat: "online-id", meetingLink: "http://x.io" }).get("link"), "http://x.io");
  });
  test("empty stays empty (clears the column) and a WhatsApp number stays a number-link", () => {
    assert.equal(build({ location_url: "" }).get("location_url"), "");
    assert.equal(build({}).get("whatsapp_link"), "https://wa.me/96555551234");
  });
});

describe("F-DEV2-4 a failed detail read is handled once", () => {
  const notFound = { response: { status: 404 } };
  const serverError = { response: { status: 500 } };
  test("404 redirects", () => assert.equal(learnServeReadErrorAction(notFound, false), "redirect"));
  test("a failed first read is left to the inline unavailable state", () => {
    assert.equal(learnServeReadErrorAction(serverError, false), "none");
  });
  test("a failed refetch over a shown record toasts", () => {
    assert.equal(learnServeReadErrorAction(serverError, true), "toast");
  });
  test("no error, nothing", () => assert.equal(learnServeReadErrorAction(null, true), "none"));
});
