import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction } from "../generated/kysely-tailordb";
import { TemplateNotFoundError } from "../lib/errors.generated";

export interface DeleteNotificationTemplateInput {
  templateId?: string;
  eventType?: string;
  channelId?: string;
  locale?: string;
}

/**
 * Hard-deletes a NotificationTemplate by id or (eventType, channelId, locale) triple; errors when no matching row exists.
 */
export async function run(
  db: Transaction,
  input: DeleteNotificationTemplateInput,
  _ctx: CommandContext,
) {
  const { templateId, eventType, channelId, locale } = input;

  let lookup = db.selectFrom("NotificationTemplate").select("id");
  if (templateId) {
    lookup = lookup.where("id", "=", templateId);
  } else if (eventType && channelId && locale) {
    lookup = lookup
      .where("eventType", "=", eventType)
      .where("channelId", "=", channelId)
      .where("locale", "=", locale);
  } else {
    return err(new TemplateNotFoundError("(no identifier supplied)"));
  }

  const existing = await lookup.executeTakeFirst();
  if (!existing) {
    return err(new TemplateNotFoundError(templateId ?? `${eventType}:${channelId}:${locale}`));
  }

  await db.deleteFrom("NotificationTemplate").where("id", "=", existing.id).execute();

  return ok({ deletedId: existing.id });
}
