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 {
  PartnerNotFoundError,
  InvalidValueError,
  DuplicateIdentificationError,
  InvalidValidityPeriodError,
} from "../lib/errors.generated";
import {
  baseActivePartner,
  baseDraftPartner,
  baseInactivePartner,
  baseTaxIdIdentification,
} from "../testing/fixtures";
import { run, type CreatePartnerIdentificationInput } from "./createPartnerIdentification";

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

  it("creates identification for DRAFT partner", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const created = { ...baseTaxIdIdentification, partnerId: baseDraftPartner.id };
    mock.enqueueResults([baseDraftPartner], [], [created]);

    const input: CreatePartnerIdentificationInput = {
      partnerId: baseDraftPartner.id,
      type: "TAX_ID",
      value: "12-3456789",
      issuingCountry: "US",
    };

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

  it("creates identification for partner", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const created = { ...baseTaxIdIdentification, partnerId: baseActivePartner.id };
    mock.enqueueResults([baseActivePartner], [], [created]);

    const input: CreatePartnerIdentificationInput = {
      partnerId: baseActivePartner.id,
      type: "TAX_ID",
      value: "12-3456789",
      issuingCountry: "US",
    };

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

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

    const input: CreatePartnerIdentificationInput = {
      partnerId: "non-existent",
      type: "TAX_ID",
      value: "12-3456789",
    };

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

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

    const input: CreatePartnerIdentificationInput = {
      partnerId: baseActivePartner.id,
      type: "TAX_ID",
      value: "",
    };

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

  it("returns error when duplicate (type, value) in company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActivePartner], [baseTaxIdIdentification]);

    const input: CreatePartnerIdentificationInput = {
      partnerId: baseActivePartner.id,
      type: "TAX_ID",
      value: "12-3456789",
    };

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

  it("returns error when validTo is before validFrom", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActivePartner], []);

    const input: CreatePartnerIdentificationInput = {
      partnerId: baseActivePartner.id,
      type: "VAT",
      value: "DE999999999",
      validFrom: new Date("2025-12-31"),
      validTo: new Date("2024-01-01"),
    };

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

  it("creates identification for INACTIVE partner", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const created = { ...baseTaxIdIdentification, partnerId: baseInactivePartner.id };
    mock.enqueueResults([baseInactivePartner], [], [created]);

    const input: CreatePartnerIdentificationInput = {
      partnerId: baseInactivePartner.id,
      type: "TAX_ID",
      value: "12-3456789",
      issuingCountry: "US",
    };

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

  it("creates with optional fields omitted", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const created = {
      ...baseTaxIdIdentification,
      partnerId: baseActivePartner.id,
      issuingCountry: null,
      validFrom: null,
      validTo: null,
    };
    mock.enqueueResults([baseActivePartner], [], [created]);

    const input: CreatePartnerIdentificationInput = {
      partnerId: baseActivePartner.id,
      type: "TAX_ID",
      value: "12-3456789",
    };

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