import type { Transaction } from "../generated/kysely-tailordb";
import { CompanyNotFoundError, InvalidNameError } from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface CreateCostCenterHierarchyInput {
  companyId: string;
  name: string;
  version: string;
}

export async function run(
  db: Transaction,
  input: CreateCostCenterHierarchyInput,
  ctx: CommandContext,
) {
  void ctx;

  // Validate company exists and is ACTIVE
  const company = await db
    .selectFrom("Company" as never)
    .where("id" as never, "=", input.companyId as never)
    .selectAll()
    .executeTakeFirst();

  if (!company || (company as Record<string, unknown>).status !== "ACTIVE") {
    return err(new CompanyNotFoundError(input.companyId));
  }

  // Validate name is non-empty
  if (!input.name || input.name.trim() === "") {
    return err(new InvalidNameError(input.companyId));
  }

  // Create hierarchy
  const hierarchy = await db
    .insertInto("CostCenterHierarchy")
    .values({
      companyId: input.companyId,
      name: input.name,
      version: input.version,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

  return ok({ hierarchy: hierarchy! });
}
