import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { DepartmentNotFoundError, InvalidStateError } from "../lib/errors.generated";
import { activeDepartment, inactiveDepartment } from "../testing/fixtures";
import { run } from "./reactivateDepartment";

describe("reactivateDepartment", () => {
  it("reactivates INACTIVE department", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const reactivated = {
      ...inactiveDepartment,
      status: "ACTIVE",
      updatedAt: new Date(),
    };

    mock.enqueueResults([inactiveDepartment], [reactivated]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department.status).toBe("ACTIVE");
      expect(result.value.department.updatedAt).not.toBeNull();
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

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

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

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

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

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