import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { CalendarInUseError, HolidayCalendarNotFoundError } from "../lib/errors.generated"; export interface DeleteHolidayCalendarInput { id: string; } /** * Function: deleteHolidayCalendar * Description: Deletes a HolidayCalendar. Rejected when the calendar is still * referenced by any CompanyHoliday entry or WorkRule, so a calendar in use is * never orphaned. */ export async function run( db: Transaction, input: DeleteHolidayCalendarInput, _ctx: CommandContext, ) { const holidayCalendar = await db .selectFrom("HolidayCalendar") .selectAll() .where("id", "=", input.id) .forUpdate() .executeTakeFirst(); if (!holidayCalendar) { return err(new HolidayCalendarNotFoundError(input.id)); } const referencingHoliday = await db .selectFrom("CompanyHoliday") .select("id") .where("calendarId", "=", input.id) .executeTakeFirst(); const referencingWorkRule = await db .selectFrom("WorkRule") .select("id") .where("holidayCalendarId", "=", input.id) .executeTakeFirst(); if (referencingHoliday || referencingWorkRule) { return err(new CalendarInUseError(input.id)); } await db.deleteFrom("HolidayCalendar").where("id", "=", input.id).execute(); return ok({ id: input.id }); }