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

export interface DeleteAllocationRuleInput {
  allocationRuleId: string;
}

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

  // Validate allocation rule exists
  const rule = await db
    .selectFrom("AllocationRule")
    .where("id", "=", input.allocationRuleId)
    .selectAll()
    .forUpdate()
    .executeTakeFirst();

  if (!rule) {
    return err(new AllocationRuleNotFoundError(input.allocationRuleId));
  }

  // Validate parent cycle is in DRAFT status
  const cycle = await db
    .selectFrom("AllocationCycle")
    .where("id", "=", rule.allocationCycleId)
    .selectAll()
    .forUpdate()
    .executeTakeFirst();

  if (cycle?.status !== "DRAFT") {
    return err(new InvalidStateError(input.allocationRuleId));
  }

  // Delete the rule
  await db.deleteFrom("AllocationRule").where("id", "=", input.allocationRuleId).execute();

  return ok({ allocationRuleId: input.allocationRuleId });
}
