import assert from "node:assert/strict";
import { test } from "node:test";
import { useVolunteerAccountSubmit } from "@/features/profile/components/useVolunteerAccountSubmit";
import { buildVolunteerAccountInitialValues } from "@/features/profile/components/volunteerAccountInitialValues";
import { birthDateInputValue } from "@/components/ui/dateInputValue";
import { buildVolunteerAccountValidation } from "@/features/profile/components/volunteerAccountValidation";
import { isUnderage } from "@/features/profile/components/volunteerAccountRules";
import type { FormikHelpers } from "formik";
import type { CombinedFormValues } from "@/features/profile/components/volunteerAccountTypes";

type Context = Parameters<typeof useVolunteerAccountSubmit>[0];

function harness(savedDob: string, succeed = true) {
  const profileCalls: unknown[] = [], accountCalls: unknown[] = [], errors: string[] = [], routes: string[] = [];
  const context = {
    t: (key: string) => key, selectedLanguage: "ar", user: null,
    updateUser: () => {}, updateProfilePic: () => {},
    accountData: { data: { first_name: "Old", last_name: "Name", birth_year: Number(savedDob.slice(0, 4)) } },
    volunteerProfile: { data: { dob: savedDob, birth_year: Number(savedDob.slice(0, 4)) } },
    router: { push: (path: string) => routes.push(path) }, genderOptions: [], genderData: undefined,
    setIsOnlyProfilePicChanged: () => {}, setComponentKey: () => {},
    updateAccountMutation: { mutateAsync: async (payload: unknown) => { accountCalls.push(payload); return {}; } },
    updateProfileMutation: { mutateAsync: async (payload: unknown) => {
      profileCalls.push(payload);
      if (!succeed) throw { response: { data: { errors: { dob: ["تاريخ الميلاد غير صالح."] } } } };
      return { key: "success", response_status: { error: false }, data: {} };
    } },
  } as unknown as Context;
  const helpers = { setFieldError: (field: string) => errors.push(field), resetForm: () => {} } as unknown as FormikHelpers<CombinedFormValues>;
  const values = { ...buildVolunteerAccountInitialValues(undefined, undefined), first_name: "New", last_name: "Name", nationality: "kuwaiti", civil_id: "299010100001", nickname: "tester", dob: savedDob };
  return { submit: (changes: Partial<CombinedFormValues>) => useVolunteerAccountSubmit(context)({ ...values, ...changes }, helpers), profileCalls, accountCalls, errors, routes, context };
}

test("adult to minor sends the new DOB and guardian together, without a preceding account write", async () => {
  const h = harness("1990-01-01");
  await h.submit({ dob: "2012-01-01", emergency_contact_name: "Parent", emergency_contact_phone: "50001111", emergency_contact_country_code: "+965", emergency_contact_civil_id: "280010100001", emergency_contact_relationship: 3 });
  assert.equal(h.accountCalls.length, 0);
  assert.equal(h.profileCalls.length, 1);
  assert.equal((h.profileCalls[0] as Record<string, unknown>).dob, "2012-01-01");
  assert.equal((h.profileCalls[0] as Record<string, unknown>).emergency_contact_name, "Parent");
  assert.equal((h.profileCalls[0] as Record<string, unknown>).first_name, "New");
  assert.deepEqual(h.routes, ["/volunteer-profile"]);
});

test("minor to adult submits the adult DOB in the same save and leaves no partial account write", async () => {
  const h = harness("2012-01-01");
  await h.submit({ dob: "1990-01-01" });
  assert.equal(h.accountCalls.length, 0);
  assert.equal((h.profileCalls[0] as Record<string, unknown>).dob, "1990-01-01");
});

test("a refused profile save keeps the form open and does not save names through another endpoint", async () => {
  const h = harness("1990-01-01", false);
  await h.submit({ dob: "2012-01-01" });
  assert.equal(h.accountCalls.length, 0);
  assert.deepEqual(h.errors, ["dob"]);
  assert.deepEqual(h.routes, []);
});

test("invalid or incomplete typed dates replace the old DOB with a value validation refuses", async () => {
  const schema = buildVolunteerAccountValidation({ t: key => key, initialDob: "1990-01-01" });
  for (const input of ["31-02-2012", "01-0", ""]) {
    const next = birthDateInputValue(input);
    assert.notEqual(next.value, "1990-01-01");
    await assert.rejects(schema.validateAt("dob", { dob: next.value }));
  }
  assert.equal(birthDateInputValue("٠١٠٢٢٠١٢").value, "2012-02-01");
});

test("stored year-only minors use the same year difference as Laravel", async context => {
  context.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-18T12:00:00Z") });
  assert.equal(isUnderage("", 2010), true);
  assert.equal(isUnderage("", 2008), false);
  assert.equal(isUnderage("2008-12-01", 2008), true);
  const schema = buildVolunteerAccountValidation({ t: key => key, storedBirthYear: 2010 });
  await assert.rejects(schema.validateAt("emergency_contact_name", { dob: "", emergency_contact_name: "" }));
});

test("guardian validation rejects the holder's own phone and civil ID but accepts a different person", async () => {
  const schema = buildVolunteerAccountValidation({ t: key => key });
  const values = { dob: "2012-01-01", country_code: "+965", phone_number: "50001111", civil_id: "299010100001", emergency_contact_country_code: "+965", emergency_contact_phone: "50001111", emergency_contact_civil_id: "299010100001" };
  await assert.rejects(schema.validateAt("emergency_contact_phone", values));
  await assert.rejects(schema.validateAt("emergency_contact_civil_id", values));
  await schema.validateAt("emergency_contact_phone", { ...values, emergency_contact_phone: "50002222" });
  await schema.validateAt("emergency_contact_civil_id", { ...values, emergency_contact_civil_id: "280010100001" });
  await assert.rejects(schema.validateAt("dob", { dob: "1899-01-01" }));
});

test("an unrelated edit with unknown age never clears saved guardian fields", async () => {
  const h = harness("");
  await h.submit({ dob: "", emergency_contact_name: "Legacy guardian", emergency_contact_phone: "50002222" });
  const payload = h.profileCalls[0] as Record<string, unknown>;
  assert.equal("emergency_contact_name" in payload, false);
  assert.equal("emergency_contact_phone" in payload, false);
});


test("saving the same values again does not resend a profile because of display objects or nulls", async () => {
  const h = harness("1990-01-01");
  await h.submit({});
  const payload = h.profileCalls[0] as Record<string, unknown>;
  h.context.accountData = { data: { ...h.context.accountData?.data, ...payload, emergency_contact_relationship_display: null } } as unknown as Context["accountData"];
  h.context.volunteerProfile = { data: { ...payload, gender_display: { id: payload.gender }, interest_display: [] } } as unknown as Context["volunteerProfile"];
  h.profileCalls.length = 0;
  await h.submit({});
  assert.equal(h.profileCalls.length, 0);
});
