import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import type { Transaction } from "../generated/kysely-tailordb"; import { DuplicateCalendarKeyError, HolidayCalendarNotFoundError } from "../lib/errors.generated"; export type UpdateHolidayCalendarInput = { id: string; } & { key?: string; name?: string; }; /** * Function: updateHolidayCalendar * Description: Corrects a HolidayCalendar's key or name in place. A key change * that collides with another calendar is rejected. */ export async function run( db: Transaction, input: UpdateHolidayCalendarInput, _ctx: CommandContext, ) { const holidayCalendar = await db .selectFrom("HolidayCalendar") .selectAll() .where("id", "=", input.id) .forUpdate() .executeTakeFirst(); if (!holidayCalendar) { return err(new HolidayCalendarNotFoundError(input.id)); } if (input.key !== undefined && input.key !== holidayCalendar.key) { const duplicate = await db .selectFrom("HolidayCalendar") .selectAll() .where("key", "=", input.key) .where("id", "!=", input.id) .forUpdate() .executeTakeFirst(); if (duplicate) { return err(new DuplicateCalendarKeyError(input.key)); } } const updates: { key?: string; name?: string } = {}; if (input.key !== undefined) updates.key = input.key; if (input.name !== undefined) updates.name = input.name; const updated = await db .updateTable("HolidayCalendar") .set(updates) .where("id", "=", input.id) .returningAll() .executeTakeFirstOrThrow(); return ok({ holidayCalendar: updated }); }