import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    const reactivatedCompany = { ...inactiveCompany, status: "ACTIVE" };
    spies.select.mockReturnValue(inactiveCompany);
    spies.update.mockReturnValue(reactivatedCompany);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(draftCompany);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(activeCompany);

    const result = await run(db, { companyId: activeCompany.id });

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