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

export interface CreateProfitCenterHierarchyInput {
  companyId: string;
  name: string;
}

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

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

  if (!company || company.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 the hierarchy
  const hierarchy = await db
    .insertInto("ProfitCenterHierarchy")
    .values({
      companyId: input.companyId,
      name: input.name,
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ profitCenterHierarchy: hierarchy });
}
