import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  IdentificationNotFoundError,
  InvalidValueError,
  DuplicateIdentificationError,
  InvalidValidityPeriodError,
} from "../lib/errors.generated";
import { baseActivePartner, baseTaxIdIdentification } from "../testing/fixtures";
import { run, type UpdatePartnerIdentificationInput } from "./updatePartnerIdentification";

describe("updatePartnerIdentification", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["business-partner:partner:updatePartnerIdentification"],
  };

  it("updates identification value", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...baseTaxIdIdentification, value: "98-7654321" };
    mock.enqueueResults([baseTaxIdIdentification], [baseActivePartner], [], [updated]);

    const input: UpdatePartnerIdentificationInput = {
      id: baseTaxIdIdentification.id,
      value: "98-7654321",
    };

    const result = await mock.withTx((trx) =>
      run(trx, input as UpdatePartnerIdentificationInput & Record<string, unknown>, ctx),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.identification).toEqual(updated);
    }
  });

  it("returns error when identification not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const input: UpdatePartnerIdentificationInput = {
      id: "non-existent",
      value: "new-value",
    };

    const result = await mock.withTx((trx) =>
      run(trx, input as UpdatePartnerIdentificationInput & Record<string, unknown>, ctx),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(IdentificationNotFoundError);
    }
  });

  it("returns error when value is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseTaxIdIdentification]);

    const input: UpdatePartnerIdentificationInput = {
      id: baseTaxIdIdentification.id,
      value: "",
    };

    const result = await mock.withTx((trx) =>
      run(trx, input as UpdatePartnerIdentificationInput & Record<string, unknown>, ctx),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidValueError);
    }
  });

  it("returns error when value is whitespace-only", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseTaxIdIdentification]);

    const input: UpdatePartnerIdentificationInput = {
      id: baseTaxIdIdentification.id,
      value: "   ",
    };

    const result = await mock.withTx((trx) =>
      run(trx, input as UpdatePartnerIdentificationInput & Record<string, unknown>, ctx),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidValueError);
    }
  });

  it("returns error when updated value creates duplicate", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseTaxIdIdentification],
      [baseActivePartner],
      [
        {
          ...baseTaxIdIdentification,
          id: "ident-other",
          value: "DUPLICATE",
        },
      ],
    );

    const input: UpdatePartnerIdentificationInput = {
      id: baseTaxIdIdentification.id,
      value: "DUPLICATE",
    };

    const result = await mock.withTx((trx) =>
      run(trx, input as UpdatePartnerIdentificationInput & Record<string, unknown>, ctx),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DuplicateIdentificationError);
    }
  });

  it("returns error when validity period is invalid", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // Existing identification with validFrom already set
    const existingWithDates = {
      ...baseTaxIdIdentification,
      validFrom: new Date("2025-06-01"),
      validTo: null,
    };
    mock.enqueueResults([existingWithDates]);

    const input: UpdatePartnerIdentificationInput = {
      id: baseTaxIdIdentification.id,
      validTo: new Date("2024-01-01"), // before existing validFrom
    };

    const result = await mock.withTx((trx) =>
      run(trx, input as UpdatePartnerIdentificationInput & Record<string, unknown>, ctx),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidValidityPeriodError);
    }
  });
});
