import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { ShiftPatternInUseError, ShiftPatternNotFoundError } from "../lib/errors.generated"; export interface DeleteShiftPatternInput { shiftPatternId: string; } /** * Function: deleteShiftPattern * Description: Removes a ShiftPattern that is no longer offered by planners. * Deletion is rejected while any Shift still references the pattern via * shiftPatternId, preserving the historical link between a Shift and its * originating template. The pattern's segments are embedded on the pattern * row (ADR-022), so they are removed together with it. */ export async function run(db: Transaction, input: DeleteShiftPatternInput, _ctx: CommandContext) { const shiftPattern = await db .selectFrom("ShiftPattern") .selectAll() .where("id", "=", input.shiftPatternId) .forUpdate() .executeTakeFirst(); if (!shiftPattern) { return err(new ShiftPatternNotFoundError(input.shiftPatternId)); } const referencingShift = await db .selectFrom("Shift") .select("id") .where("shiftPatternId", "=", input.shiftPatternId) .executeTakeFirst(); if (referencingShift) { return err(new ShiftPatternInUseError(input.shiftPatternId)); } await db.deleteFrom("ShiftPattern").where("id", "=", input.shiftPatternId).execute(); return ok({}); }