import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";

export interface GetNotificationTemplateInput {
  id?: string;
  eventType?: string;
  channelId?: string;
  locale?: string;
}

/**
 * Returns a NotificationTemplate by id or (eventType, channelId, locale) triple, or null; applies no default-locale fallback.
 */
export async function run(db: ReadonlyDB<DB>, input: GetNotificationTemplateInput) {
  let query = db.selectFrom("NotificationTemplate").selectAll();

  if (input.id) {
    query = query.where("id", "=", input.id);
  } else if (input.eventType && input.channelId && input.locale) {
    query = query
      .where("eventType", "=", input.eventType)
      .where("channelId", "=", input.channelId)
      .where("locale", "=", input.locale);
  } else {
    return ok({ template: null });
  }

  const template = await query.executeTakeFirst();
  return ok({ template: template ?? null });
}
