import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DepartmentStatus } from "../db/department.lifecycle.generated";
import type { DB } from "../generated/kysely-tailordb";

export interface GetDepartmentChildrenInput {
  departmentId: string;
  status?: DepartmentStatus;
}

export async function run(db: ReadonlyDB<DB>, input: GetDepartmentChildrenInput) {
  let query = db
    .selectFrom("Department")
    .selectAll()
    .where("parentDepartmentId", "=", input.departmentId);

  if (input.status !== undefined) {
    query = query.where("status", "=", input.status);
  }

  const departments = await query.execute();
  return ok({ departments });
}
