import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    const reactivated = {
      ...inactiveDepartment,
      status: "ACTIVE",
      updatedAt: new Date(),
    };

    spies.select.mockReturnValueOnce(inactiveDepartment); // find department
    spies.update.mockReturnValue(reactivated);

    const result = await run(db, {
      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(spies.update).toHaveBeenCalled();
  });

  it("throws when department does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

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

    const result = await run(db, {
      departmentId: activeDepartment.id,
    });

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