import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PartnerNotFoundError,
  InvalidIdentificationTypeError,
  InvalidValueError,
  DuplicateIdentificationError,
  InvalidValidityPeriodError,
} from "../lib/errors.generated";
import {
  baseActivePartner,
  baseDraftPartner,
  baseInactivePartner,
  baseTaxIdIdentification,
} from "../testing/fixtures";
import { run, type CreatePartnerIdentificationInput } from "./createPartnerIdentification";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("creates identification for DRAFT partner", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // First select: partner lookup -> found (DRAFT)
    spies.select.mockReturnValueOnce(baseDraftPartner);
    // Second select: duplicate check -> no duplicate
    spies.select.mockReturnValueOnce(undefined);
    // Insert: return created identification
    const created = { ...baseTaxIdIdentification, partnerId: baseDraftPartner.id };
    spies.insert.mockReturnValueOnce(created);

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

    const result = await run(
      db,
      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 { db, spies } = createMockDb<Transaction>();
    // First select: partner lookup -> found
    spies.select.mockReturnValueOnce(baseActivePartner);
    // Second select: duplicate check -> no duplicate
    spies.select.mockReturnValueOnce(undefined);
    // Insert: return created identification
    const created = { ...baseTaxIdIdentification, partnerId: baseActivePartner.id };
    spies.insert.mockReturnValueOnce(created);

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

    const result = await run(
      db,
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

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

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

  it("returns error when type is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActivePartner);

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

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

  it("returns error when value is empty", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActivePartner);

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

    const result = await run(
      db,
      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 { db, spies } = createMockDb<Transaction>();
    // Partner found
    spies.select.mockReturnValueOnce(baseActivePartner);
    // Duplicate found
    spies.select.mockReturnValueOnce(baseTaxIdIdentification);

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

    const result = await run(
      db,
      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 { db, spies } = createMockDb<Transaction>();
    // Partner found
    spies.select.mockReturnValueOnce(baseActivePartner);
    // No duplicate
    spies.select.mockReturnValueOnce(undefined);

    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 run(
      db,
      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 { db, spies } = createMockDb<Transaction>();
    // First select: partner lookup -> found (INACTIVE)
    spies.select.mockReturnValueOnce(baseInactivePartner);
    // Second select: duplicate check -> no duplicate
    spies.select.mockReturnValueOnce(undefined);
    // Insert: return created identification
    const created = { ...baseTaxIdIdentification, partnerId: baseInactivePartner.id };
    spies.insert.mockReturnValueOnce(created);

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

    const result = await run(
      db,
      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 { db, spies } = createMockDb<Transaction>();
    // First select: partner lookup -> found
    spies.select.mockReturnValueOnce(baseActivePartner);
    // Second select: duplicate check -> no duplicate
    spies.select.mockReturnValueOnce(undefined);
    // Insert: return created identification with nulls for optional fields
    const created = {
      ...baseTaxIdIdentification,
      partnerId: baseActivePartner.id,
      issuingCountry: null,
      validFrom: null,
      validTo: null,
    };
    spies.insert.mockReturnValueOnce(created);

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

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