import assert from "node:assert/strict";
import { describe, test, mock } from "node:test";
import moment from "moment";
import { YupStrongPassword } from "@/features/shared/schemas";
import { audienceAgeSchema, authoringCalendarDay, clampAudienceAge, isAuthoringDayNotPast } from "@/features/shared/opportunityFormRules";
import { buildLearnServeValidationSchema } from "@/features/opportunities/components/learnServeValidation";
import { buildVolunteerValidationSchema } from "@/features/opportunities/components/volunteerValidation";
import { buildOrganizerAccountValidation } from "@/features/profile/components/organizerAccountValidation";
import { formatDateToYYYYMMDD } from "@/lib/helpers";
import { feedbackComment, feedbackDraftErrors } from "@/features/opportunities/feedbackPolicy";
import { eventTimeRange } from "@/features/events/eventClock";
import { buildGoogleCalendarUrl, buildIcsContent, resolveSchedule } from "@/components/shared/icsCalendar";
import apiClient from "@/lib/api/client";
import { emailVerificationRequest, resendOtpRequest, forgotPasswordRequest, changePasswordRequest } from "@/features/auth/services/authApi";
import { createOpportunityFeedback, updateOpportunityFeedback, deleteOpportunityFeedback, getOpportunityFeedbacks } from "@/features/opportunities/services/feedbacks";

const development = buildLearnServeValidationSchema({ developmentPaid: true, isLicenseRequired: false, modifiedOpportunityImages: [], courseTypeId: "course", internshipTypeId: "internship" });
const volunteering = buildVolunteerValidationSchema({ isLicenseRequired: false, modifiedOpportunityImages: [], showOpportunitySection: true });

describe("PDF pages 7/42: the approved password requirements", () => {
  test("a valid eight-character password does not require a special symbol", async () => {
    assert.equal(await YupStrongPassword.validate("Abcdefg1"), "Abcdefg1");
    await YupStrongPassword.validate("Abcdef1!");
  });
  test("short, all-lowercase and digit-less passwords are still invalid", async () => {
    for (const value of ["Abcdef1", "abcdefg1", "Abcdefgh"]) await assert.rejects(YupStrongPassword.validate(value));
  });
});

describe("PDF pages 15/18/22/42: audience ages are 7 through 120", () => {
  test("the shared input keeps valid ages above 100 and clamps to the reviewed bounds", () => {
    for (const value of [7, 100, 110, 120]) assert.equal(clampAudienceAge(value), value);
    assert.equal(clampAudienceAge(6), 7); assert.equal(clampAudienceAge(121), 120);
  });
  test("both opportunity forms require a minimum and allow an empty maximum", async () => {
    for (const schema of [development, volunteering]) {
      for (const age of [[], [null, null], [null, 120], [6, 120], [7, 121], [7.5, 120], [30, 20]]) await assert.rejects(schema.validateAt("age", { age }));
      for (const age of [[7, 120], [7, null], [7]]) await schema.validateAt("age", { age });
    }
  });
  test("event ages are optional but still bounded and ordered when supplied", async () => {
    const schema = audienceAgeSchema(false);
    for (const age of [[null, null], [7, null], [null, 120], [7, 120]]) await schema.validate(age);
    for (const age of [[7, 121], [6, 20], [30, 20], [7, 20.5]]) await assert.rejects(schema.validate(age));
  });
});

describe("PDF page 18: nationality applies to course and internship only", () => {
  test("certificate-bearing types need one of the actual offered nationality values", async () => {
    for (const learningType of ["course", "internship"]) {
      for (const opportunity_nationality of ["", "non_arabic", "unknown"]) await assert.rejects(development.validateAt("opportunity_nationality", { learningType, opportunity_nationality }));
      for (const opportunity_nationality of ["all", "kuwaitis", "non_kuwaiti_arabic"]) await development.validateAt("opportunity_nationality", { learningType, opportunity_nationality });
    }
  });
  test("workshop and space have no hidden required nationality", async () => {
    for (const learningType of ["workshop", "space"]) await development.validateAt("opportunity_nationality", { learningType, opportunity_nationality: "" });
  });
});

describe("PDF pages 3/37: authoring calendar days and the Kuwait clock", () => {
  test("bare dates survive payload formatting in every host timezone", () => {
    assert.equal(formatDateToYYYYMMDD("2027-03-05"), "2027-03-05");
    assert.equal(formatDateToYYYYMMDD(new Date(2027, 2, 5)), "2027-03-05");
    assert.equal(authoringCalendarDay(new Date(2027, 2, 5).toISOString()), "2027-03-05");
    assert.equal(authoringCalendarDay("2027-02-30"), "");
  });
  test("today is the Kuwait day, even while the browser's day is different", () => {
    const now = moment.parseZone("2026-11-01T22:30:00Z");
    assert.equal(isAuthoringDayNotPast("2026-11-01", now), false);
    assert.equal(isAuthoringDayNotPast("2026-11-02", now), true);
    assert.equal(isAuthoringDayNotPast("2026-11-03", now), true);
  });
  test("Yup's extra test-context argument cannot be mistaken for a clock", async () => {
    const day = moment().utcOffset(180).locale("en").format("YYYY-MM-DD");
    for (const schema of [development, volunteering]) await schema.validateAt("startDate", { startDate: day });
  });
});

describe("PDF page 9: account editing retains required organization identity/contact", () => {
  const schema = buildOrganizerAccountValidation({ t: key => key, orgTypeOptions: [], keptDocIds: [] });
  test("name and at least one complete social link cannot be cleared", async () => {
    await assert.rejects(schema.validateAt("company_name", { company_name: "  " }));
    await schema.validateAt("company_name", { company_name: "Fursa" });
    for (const socialMedia of [[], [{ platform: "", link: "" }]]) await assert.rejects(schema.validateAt("socialMedia", { socialMedia }));
  });
  test("a valid wa.me contact works on edit as it does on signup", async () => {
    await schema.validateAt("socialMedia", { socialMedia: [{ platform: "whatsapp", link: "https://wa.me/96599999999" }] });
    await assert.rejects(schema.validateAt("socialMedia", { socialMedia: [{ platform: "whatsapp", link: "not-a-url" }] }));
  });
});

describe("PDF pages 37/38: reviews have visible validation and retain authored text", () => {
  test("reviews need an integer rating 1..5 and nonblank text", () => {
    assert.deepEqual(feedbackDraftErrors({ rating: 0, comment: "  " }, "Required"), { rating: "Required", comment: "Required" });
    for (const rating of [0, 6, 2.5]) assert.equal(feedbackDraftErrors({ rating, comment: "Comment" }, "Required").rating, "Required");
    assert.deepEqual(feedbackDraftErrors({ rating: 5, comment: "تعليق" }, "Required"), {});
  });
  test("reading and editing under the other UI language retains the original comment", () => {
    assert.equal(feedbackComment({ comment_ar: "تعليق", comment_en: null }, "en"), "تعليق");
    assert.equal(feedbackComment({ comment_ar: null, comment_en: "Comment" }, "ar"), "Comment");
  });
});

describe("PDF pages 22/27/37: optional event clocks and external calendar", () => {
  const t = (key: string) => key === "COMMON.AM" ? "AM" : "PM";
  test("missing clocks show no Invalid date and one clock works independently", () => {
    assert.equal(eventTimeRange(null, null, t), "");
    assert.equal(eventTimeRange("09:30", null, t), "09:30 AM");
    assert.equal(eventTimeRange(null, "16:00:00", t), "04:00 PM");
  });
  test("AM/PM follows the hour even when Moment's global locale is Arabic", () => {
    const old = moment.locale(); moment.locale("ar");
    try { assert.equal(eventTimeRange("09:30:00", "16:00", t), "09:30 AM - 04:00 PM"); }
    finally { moment.locale(old); }
  });
  test("Google/ICS use Kuwait instants regardless of the browser timezone", () => {
    const schedule = resolveSchedule({ start_date: "2026-11-01", end_date: "2026-11-01", start_time: "09:00", end_time: "11:00" })!;
    assert.equal(schedule.start?.toISOString(), "2026-11-01T06:00:00.000Z");
    assert.match(buildIcsContent(schedule, "Event", "Kuwait"), /DTSTART:20261101T060000Z/);
    assert.equal(new URL(buildGoogleCalendarUrl(schedule, "Event", "Kuwait")).searchParams.get("dates"), "20261101T060000Z/20261101T080000Z");
  });
  test("an overnight session exports its real next-day end", () => {
    const schedule = resolveSchedule({ start_date: "2026-11-01", start_time: "22:00", end_time: "01:00" })!;
    assert.equal(schedule.end?.toISOString(), "2026-11-01T22:00:00.000Z");
    assert.equal(schedule.end!.getTime() - schedule.start!.getTime(), 3 * 3600000);
  });
});

describe("PDF page 37: HTTP 200 failures cannot be reported as successful writes", () => {
  const failure = { key: "fail", response_status: { error: true, validation_errors: { otp: ["Expired"] } } };
  test("OTP, resend, reset and forgot-password reject a failure envelope", async () => {
    const stub = mock.method(apiClient, "post", async () => ({ data: failure }));
    try {
      await assert.rejects(emailVerificationRequest({ email: "user@example.test", type: "register", otp: "123456" }), e => e === failure);
      await assert.rejects(resendOtpRequest({ email: "user@example.test", type: "register" }), e => e === failure);
      await assert.rejects(forgotPasswordRequest({ email: "user@example.test" }), e => e === failure);
      await assert.rejects(changePasswordRequest({ email: "user@example.test", password: "Abcdefg1" }), e => e === failure);
    } finally { stub.mock.restore(); }
  });
  test("review read/create/update/delete reject failure envelopes", async () => {
    const post = mock.method(apiClient, "post", async () => ({ data: failure }));
    const patch = mock.method(apiClient, "patch", async () => ({ data: failure }));
    const del = mock.method(apiClient, "delete", async () => ({ data: failure }));
    const get = mock.method(apiClient, "get", async () => ({ data: failure }));
    try {
      await assert.rejects(createOpportunityFeedback({ learn_serve_opportunity_id: 1, rating: 5, comment_ar: "تعليق" }), e => e === failure);
      await assert.rejects(updateOpportunityFeedback({ feedback_id: "1", data: { rating: 4 } }), e => e === failure);
      await assert.rejects(deleteOpportunityFeedback("1"), e => e === failure);
      await assert.rejects(getOpportunityFeedbacks("1"), e => e === failure);
    } finally { post.mock.restore(); patch.mock.restore(); del.mock.restore(); get.mock.restore(); }
  });
});

test("an explicit failure envelope uses the common API error path without contacting a server", async () => {
  const data = { key: "fail", msg: "Rejected", response_status: { error: true, validation_errors: { field: ["Invalid"] } } };
  await assert.rejects(apiClient.get("/audit-local-adapter/", { adapter: async config => ({ data, status: 200, statusText: "OK", headers: {}, config }) }), (error: unknown) => {
    const response = (error as { response?: { status: number; data: unknown } }).response;
    assert.equal(response?.status, 200); assert.deepEqual(response?.data, data); return true;
  });
  const result = await apiClient.get("/audit-local-adapter/", { adapter: async config => ({ data: { key: "success", data: [] }, status: 200, statusText: "OK", headers: {}, config }) });
  assert.deepEqual(result.data.data, []);
  const blob = new Blob(["%PDF-test"], { type: "application/pdf" });
  const pdf = await apiClient.get("/audit-local-adapter/", { adapter: async config => ({ data: blob, status: 200, statusText: "OK", headers: {}, config }) });
  assert.equal(pdf.data, blob);
});

test("calendar picker minimum represents Kuwait's day even at a different local midnight", async () => {
  const { kuwaitDatePickerMinimum } = await import("@/features/shared/opportunityFormRules");
  const minimum = kuwaitDatePickerMinimum(moment.parseZone("2026-11-01T22:30:00Z"));
  assert.equal(minimum.getFullYear(), 2026); assert.equal(minimum.getMonth(), 10); assert.equal(minimum.getDate(), 2);
});

test("completed registration is not proof of absence before preparation is finalized", async () => {
  const { cardStatusBadges } = await import("@/features/opportunities/cardStatusBadges");
  const item = { has_ended: true, profile_activity_tag: "registered" };
  const pending = cardStatusBadges(item, "profile-individual", false).map(b => b.label);
  assert.ok(!pending.includes("COMMON.PROFILE_BADGE_ABSENT"));
  assert.ok(cardStatusBadges({ ...item, owner_attendance_status: "absent" }, "profile-individual", false).some(b => b.label === "COMMON.PROFILE_BADGE_ABSENT"));
});

test("card state follows actual session dates ahead of stale backend flags", async () => {
  const { cardStatusBadges } = await import("@/features/opportunities/cardStatusBadges");
  const future = cardStatusBadges({ start_date: "2099-01-01", end_date: "2099-01-02", opportunity_status: "completed", has_ended: true }, "viewer", false);
  assert.ok(!future.some(b => b.label === "COMMON.ENDED"));
  const past = cardStatusBadges({ start_date: "2000-01-01", end_date: "2000-01-02", opportunity_status: "upcoming" }, "viewer", false);
  assert.ok(past.some(b => b.label === "COMMON.ENDED"));
});

test("personal and guardian names accept Arabic without changing the username format", async () => {
  const { buildVolunteerAccountValidation } = await import("@/features/profile/components/volunteerAccountValidation");
  const schema = buildVolunteerAccountValidation({ t: key => key });
  await schema.validateAt("first_name", { first_name: "أحمد" });
  await schema.validateAt("last_name", { last_name: "عبد الله" });
  await schema.validateAt("emergency_contact_name", { emergency_contact_name: "محمد أحمد", dob: "2020-01-01" });
  await assert.rejects(schema.validateAt("nickname", { nickname: "أحمد" }));
});
