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

describe("getDepartmentChildren", () => {
  it("returns direct children of department", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([childDepartment]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.departments).toEqual([childDepartment]);
      expect(result.value.departments).toHaveLength(1);
    }
  });

  it("returns empty list when department has no children", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.departments).toEqual([]);
    }
  });

  it("filters children by ACTIVE status", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([childDepartment]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.departments).toEqual([childDepartment]);
    }
  });

  it("filters children by INACTIVE status", async () => {
    const { db, spies } = createMockDb<DB>();
    const inactiveChild = { ...childDepartment, status: "INACTIVE" as const };
    spies.select.mockReturnValueOnce([inactiveChild]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.departments).toEqual([inactiveChild]);
    }
  });

  it("does not return grandchildren", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([childDepartment]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.departments).not.toContainEqual(grandchildDepartment);
    }
  });
});
