import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } 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";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("updates identification value", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // First select: existing identification found
    spies.select.mockReturnValueOnce(baseTaxIdIdentification);
    // Second select: partner lookup for company scope
    spies.select.mockReturnValueOnce(baseActivePartner);
    // Third select: duplicate check -> no duplicate
    spies.select.mockReturnValueOnce(undefined);
    // Update: return updated identification
    const updated = { ...baseTaxIdIdentification, value: "98-7654321" };
    spies.update.mockReturnValueOnce(updated);

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

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

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

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

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

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

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

    const result = await run(
      db,
      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 { db, spies } = createMockDb<Transaction>();
    // Existing identification found
    spies.select.mockReturnValueOnce(baseTaxIdIdentification);
    // Partner lookup
    spies.select.mockReturnValueOnce(baseActivePartner);
    // Duplicate found
    spies.select.mockReturnValueOnce({
      ...baseTaxIdIdentification,
      id: "ident-other",
      value: "DUPLICATE",
    });

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

    const result = await run(
      db,
      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 { db, spies } = createMockDb<Transaction>();
    // Existing identification with validFrom already set
    const existingWithDates = {
      ...baseTaxIdIdentification,
      validFrom: new Date("2025-06-01"),
      validTo: null,
    };
    spies.select.mockReturnValueOnce(existingWithDates);

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

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