import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { WorkRuleInUseError, WorkRuleNotFoundError } from "../lib/errors.generated"; export interface DeleteWorkRuleInput { id: string; } /** * Function: deleteWorkRule * Description: Removes a WorkRule generation, but only when no current * assignment references it, so an assigned worker can never lose their rule * unexpectedly. * * A WorkRule is "in use" — and so undeletable — when a current WorkRuleAssignment binds it to a * target (assignWorkRule persists these), or when an in-force EligibilityRule grants it (grantType * WORK_RULE). Either reference means removing the rule would strand live configuration. */ export async function run(db: Transaction, input: DeleteWorkRuleInput, _ctx: CommandContext) { const workRule = await db .selectFrom("WorkRule") .selectAll() .where("id", "=", input.id) .forUpdate() .executeTakeFirst(); if (!workRule) { return err(new WorkRuleNotFoundError(input.id)); } const referencingAssignment = await db .selectFrom("WorkRuleAssignment") .select("id") .where("workRuleId", "=", input.id) .where("effectiveEnd", "is", null) .executeTakeFirst(); if (referencingAssignment) { return err(new WorkRuleInUseError(input.id)); } const referencingGrant = await db .selectFrom("EligibilityRule") .selectAll() .where("grantType", "=", "WORK_RULE") .where("workRuleId", "=", input.id) .where("effectiveEnd", "is", null) .executeTakeFirst(); if (referencingGrant) { return err(new WorkRuleInUseError(input.id)); } await db.deleteFrom("WorkRule").where("id", "=", input.id).execute(); return ok({}); }