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

export type GetDepartmentInput = { id: string } | { code: string; companyId: string };

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

  if ("id" in input) {
    query = query.where("id", "=", input.id);
  } else {
    query = query.where("code", "=", input.code).where("companyId", "=", input.companyId);
  }

  const department = await query.executeTakeFirst();
  return ok({ department: department ?? null });
}
