import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { activeDepartment, inactiveDepartment } from "../testing/fixtures";
import { run } from "./getDepartment";

describe("getDepartment", () => {
  it("returns department when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activeDepartment);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department).toEqual(activeDepartment);
    }
  });

  it("returns department when found by code and companyId", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activeDepartment);

    const result = await run(db, {
      code: activeDepartment.code,
      companyId: activeDepartment.companyId,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department).toEqual(activeDepartment);
    }
  });

  it("returns null when department not found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "nonexistent-id" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department).toBeNull();
    }
  });

  it("returns null when department not found by code", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, {
      code: "NONEXISTENT",
      companyId: activeDepartment.companyId,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department).toBeNull();
    }
  });

  it("returns ACTIVE department", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activeDepartment);

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

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

  it("returns INACTIVE department", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(inactiveDepartment);

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

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