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 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" 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 the hierarchy
  const hierarchy = await db
    .insertInto("ProfitCenterHierarchy")
    .values({
      companyId: input.companyId,
      name: input.name,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

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