import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { EligibilityRuleNotFoundError, SoleGrantInUseError } from "../lib/errors.generated"; export interface DeleteEligibilityRuleInput { id: string; } export async function run( db: Transaction, input: DeleteEligibilityRuleInput, _ctx: CommandContext, ) { const eligibilityRule = await db .selectFrom("EligibilityRule") .selectAll() .where("id", "=", input.id) .forUpdate() .executeTakeFirst(); if (!eligibilityRule) { return err(new EligibilityRuleNotFoundError(input.id)); } // A WORK_RULE grant may be the eligibility basis a current WorkRuleAssignment relies on // (assignWorkRule requires an in-force grant for the target). If a current assignment binds this // rule's (targetType, targetId, workRuleId) and no OTHER in-force grant covers the same // combination, deleting this generation would strand that assignment — reject it (SOLE_GRANT_IN_USE). if (eligibilityRule.grantType === "WORK_RULE" && eligibilityRule.workRuleId != null) { const dependentAssignment = await db .selectFrom("WorkRuleAssignment") .select("id") .where("targetType", "=", eligibilityRule.targetType) .where("targetId", "=", eligibilityRule.targetId) .where("workRuleId", "=", eligibilityRule.workRuleId) .where("effectiveEnd", "is", null) .executeTakeFirst(); if (dependentAssignment) { const otherGrant = await db .selectFrom("EligibilityRule") .select("id") .where("id", "!=", input.id) .where("grantType", "=", "WORK_RULE") .where("targetType", "=", eligibilityRule.targetType) .where("targetId", "=", eligibilityRule.targetId) .where("workRuleId", "=", eligibilityRule.workRuleId) .where("effectiveEnd", "is", null) .executeTakeFirst(); if (!otherGrant) { return err(new SoleGrantInUseError(input.id)); } } } await db.deleteFrom("EligibilityRule").where("id", "=", input.id).execute(); return ok({ eligibilityRule }); }