import assert from "node:assert/strict";
import { test } from "node:test";
import apiClient from "@/lib/api/client";
import { updateOrganizerProfile } from "@/features/profile/services/profileApi";
import { buildOrganizerAccountValidation } from "@/features/profile/components/organizerAccountValidation";

const schema = buildOrganizerAccountValidation({ t: key => key, orgTypeOptions: [], keptDocIds: [] });

test("internal licence accepts one supported file up to 10 MB", async () => {
  await schema.validateAt("internal_license_files", { internal_license_files: [new File(["pdf"], "licence.pdf")] });
  await assert.rejects(schema.validateAt("internal_license_files", { internal_license_files: [new File(["exe"], "licence.exe")] }));
  await assert.rejects(schema.validateAt("internal_license_files", { internal_license_files: [new File([new Uint8Array(10 * 1024 * 1024 + 1)], "licence.pdf")] }));
  await assert.rejects(schema.validateAt("internal_license_files", { internal_license_files: [new File([], "a.pdf"), new File([], "b.pdf")] }));
});

test("replacement sends multipart with PATCH spoofing; removal uses the supported flag", async () => {
  const previous = apiClient.defaults.adapter;
  const file = new File(["pdf"], "licence.pdf", { type: "application/pdf" });
  let calls = 0;
  apiClient.defaults.adapter = async config => {
    calls++;
    assert.equal(config.url, "/organization-profile/");
    if (calls === 1) {
      assert.equal(config.method, "post");
      assert.ok(config.data instanceof FormData);
      assert.equal(config.data.get("_method"), "PATCH");
      assert.equal((config.data.get("internal_license_document") as File).name, "licence.pdf");
      assert.deepEqual(config.data.getAll("interest_ids[]"), ["1", "2"]);
    } else {
      assert.equal(config.method, "patch");
      assert.equal(JSON.parse(config.data).internal_license_document_removed, true);
    }
    return { data: { data: {} }, status: 200, statusText: "OK", headers: {}, config };
  };
  try {
    await updateOrganizerProfile({ internal_license_document: file, interest_ids: [1, 2] });
    await updateOrganizerProfile({ internal_license_document_removed: true });
    assert.equal(calls, 2);
  } finally {
    apiClient.defaults.adapter = previous;
  }
});
