import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { CompanyNotFoundError, InvalidStateError } from "../lib/errors.generated";
import { activeCompany, draftCompany, inactiveCompany } from "../testing/fixtures";
import { run } from "./deactivateCompany";

describe("deactivateCompany", () => {
  it("deactivates ACTIVE company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedCompany = { ...activeCompany, status: "INACTIVE" };
    mock.enqueueResults([activeCompany], [deactivatedCompany]);

    const result = await mock.withTx((trx) => run(trx, { companyId: activeCompany.id }));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.company.status).toBe("INACTIVE");
    }
  });

  it("throws when company does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { companyId: "nonexistent" }));

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

  it("throws when company is in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftCompany]);

    const result = await mock.withTx((trx) => run(trx, { companyId: draftCompany.id }));

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

  it("throws when company is already INACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactiveCompany]);

    const result = await mock.withTx((trx) => run(trx, { companyId: inactiveCompany.id }));

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