import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([childDepartment]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.departments).toEqual([childDepartment]);
      expect(result.value.departments).toHaveLength(1);
    }
    expect(mock.selects).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain(activeDepartment.id);
    expect(mock.selects[0].sql).toMatch(/"parentDepartmentId"/);
  });

  it("returns empty list when department has no children", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([childDepartment]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.departments).toEqual([childDepartment]);
    }
    expect(mock.selects[0].parameters).toContain("ACTIVE");
    expect(mock.selects[0].sql).toMatch(/"status"/);
  });

  it("filters children by INACTIVE status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const inactiveChild = { ...childDepartment, status: "INACTIVE" as const };
    mock.enqueueResults([inactiveChild]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.departments).toEqual([inactiveChild]);
    }
    expect(mock.selects[0].parameters).toContain("INACTIVE");
    expect(mock.selects[0].sql).toMatch(/"status"/);
  });

  it("does not return grandchildren", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([childDepartment]);

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

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