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 "./reactivateCompany";

describe("reactivateCompany", () => {
  it("reactivates INACTIVE company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const reactivatedCompany = { ...inactiveCompany, status: "ACTIVE" };
    mock.enqueueResults([inactiveCompany], [reactivatedCompany]);

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

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

  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 ACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activeCompany]);

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

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