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, PartnerNotActiveError } from "../lib/errors.generated";
import { baseActivePartner, baseInactivePartner, baseCustomerRole } from "../testing/fixtures";
import { run } from "./removeRoleFromPartner";

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

describe("removeRoleFromPartner", () => {
  it("removes CUSTOMER from partner holding both roles", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActivePartner], [baseCustomerRole], []);

    const result = await mock.withTx((trx) =>
      run(trx, { partnerId: "partner-2", role: "CUSTOMER" }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.deleted).toBe(true);
    }
    expect(mock.deletes.length).toBeGreaterThan(0);
  });

  it("idempotent when role not present", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActivePartner], []);

    const result = await mock.withTx((trx) =>
      run(trx, { partnerId: "partner-2", role: "SUPPLIER" }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.deleted).toBe(true);
    }
    expect(mock.deletes).toHaveLength(0);
  });

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

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseInactivePartner]); // partner in INACTIVE

    const result = await mock.withTx((trx) =>
      run(trx, { partnerId: "partner-3", role: "CUSTOMER" }, ctx),
    );

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