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

export type UpdateAllocationCycleInput = {
  allocationCycleId: string;
  name: string;
};
export async function run(db: Transaction, input: UpdateAllocationCycleInput, ctx: CommandContext) {
  void ctx;

  // Validate allocation cycle exists
  const cycle = await db
    .selectFrom("AllocationCycle")
    .where("id", "=", input.allocationCycleId)
    .selectAll()
    .forUpdate()
    .executeTakeFirst();

  if (!cycle) {
    return err(new AllocationCycleNotFoundError(input.allocationCycleId));
  }

  // Validate status is DRAFT
  if (cycle.status !== "DRAFT") {
    return err(new InvalidStateError(input.allocationCycleId));
  }

  // Update name
  const allocationCycle = await db
    .updateTable("AllocationCycle")
    .set({
      name: input.name,
      updatedAt: new Date(),
    })
    .where("id", "=", input.allocationCycleId)
    .returningAll()
    .executeTakeFirst();

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