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

export interface DeleteProfitCenterInput {
  profitCenterId: string;
}

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

  // Validate profit center exists
  const profitCenter = await db
    .selectFrom("ProfitCenter")
    .selectAll()
    .where("id", "=", input.profitCenterId)
    .forUpdate()
    .executeTakeFirst();

  if (!profitCenter) {
    return err(new ProfitCenterNotFoundError(input.profitCenterId));
  }

  // Only DRAFT can be deleted
  if (profitCenter.status !== "DRAFT") {
    return err(new InvalidStateError(input.profitCenterId));
  }

  // Remove all hierarchy assignments
  await db
    .deleteFrom("ProfitCenterHierarchyAssignment")
    .where("profitCenterId", "=", input.profitCenterId)
    .execute();

  // Delete the profit center
  await db.deleteFrom("ProfitCenter").where("id", "=", input.profitCenterId).executeTakeFirst();

  return ok({ profitCenter });
}
