import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { IdentificationNotFoundError } from "../lib/errors.generated";
import { baseTaxIdIdentification } from "../testing/fixtures";
import { run, type DeletePartnerIdentificationInput } from "./deletePartnerIdentification";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("deletes an existing identification", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // Select: identification found
    spies.select.mockReturnValueOnce(baseTaxIdIdentification);
    // Delete: succeeds
    spies.delete.mockReturnValueOnce(undefined);

    const input: DeletePartnerIdentificationInput = {
      id: baseTaxIdIdentification.id,
    };

    const result = await run(db, input, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.id).toBe(baseTaxIdIdentification.id);
    }
  });

  it("returns error when identification not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const input: DeletePartnerIdentificationInput = {
      id: "non-existent",
    };

    const result = await run(db, input, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(IdentificationNotFoundError);
    }
  });
});
