import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  InvalidRoleError,
  PartnerNotFoundError,
  PartnerNotActiveError,
} from "../lib/errors.generated";
import { baseActivePartner, baseInactivePartner, baseCustomerRole } from "../testing/fixtures";
import { run } from "./removeRoleFromPartner";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

const ctx: CommandContext = {
  actorId: "test-actor",
  permissions: ["business-partner:removeRoleFromPartner"],
};

describe("removeRoleFromPartner", () => {
  it("removes CUSTOMER from partner holding both roles", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActivePartner); // partner lookup
    spies.select.mockReturnValueOnce(baseCustomerRole); // existing role found
    spies.delete.mockReturnValue(undefined);

    const result = await run(db, { partnerId: "partner-2", role: "CUSTOMER" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.deleted).toBe(true);
    }
    expect(spies.delete).toHaveBeenCalled();
  });

  it("idempotent when role not present", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActivePartner); // partner lookup
    spies.select.mockReturnValueOnce(undefined); // no existing role

    const result = await run(db, { partnerId: "partner-2", role: "SUPPLIER" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.deleted).toBe(true);
    }
    expect(spies.delete).not.toHaveBeenCalled();
  });

  it("returns error for invalid role value", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(db, { partnerId: "partner-2", role: "INVALID_ROLE" }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidRoleError);
    }
  });

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

    const result = await run(db, { partnerId: "nonexistent", role: "CUSTOMER" }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(PartnerNotFoundError);
    }
  });

  it("returns error when partner is INACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInactivePartner); // partner in INACTIVE

    const result = await run(db, { partnerId: "partner-3", role: "CUSTOMER" }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(PartnerNotActiveError);
    }
  });
});
