// Channel/template lookups shared by the dispatch engine's PERSONAL stage
// (internal/planNotification) and DESTINATION stage (internal/planDestinations).

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

export const DEFAULT_LOCALE = "en-US";

type NotificationChannelId = (typeof NOTIFICATION_CHANNEL_IDS)[number];

function isNotificationChannelId(value: string): value is NotificationChannelId {
  return (NOTIFICATION_CHANNEL_IDS as readonly string[]).includes(value);
}

export interface ChannelRow {
  id: string;
  channelId: string;
  kind: "PERSONAL" | "DESTINATION";
  enabled: boolean;
}

export interface TemplateRow {
  id: string;
  eventType: string;
  channelId: string;
  locale: string;
  subject: string;
  body: string;
  htmlBody: string | null;
  variableSchema: string;
}

export async function loadChannelByChannelId(db: ReadonlyDB<DB>, channelId: string) {
  if (!isNotificationChannelId(channelId)) return undefined;
  return (await db
    .selectFrom("NotificationChannel")
    .selectAll()
    .where("channelId", "=", channelId)
    .executeTakeFirst()) as ChannelRow | undefined;
}

export async function loadChannelById(db: ReadonlyDB<DB>, id: string) {
  return (await db
    .selectFrom("NotificationChannel")
    .selectAll()
    .where("id", "=", id)
    .executeTakeFirst()) as ChannelRow | undefined;
}

async function loadTemplate(
  db: ReadonlyDB<DB>,
  eventType: string,
  channelDbId: string,
  locale: string,
): Promise<TemplateRow | undefined> {
  return (await db
    .selectFrom("NotificationTemplate")
    .selectAll()
    .where("eventType", "=", eventType)
    .where("channelId", "=", channelDbId)
    .where("locale", "=", locale)
    .executeTakeFirst()) as TemplateRow | undefined;
}

// Exact locale first, then the DEFAULT_LOCALE fallback.
export async function loadTemplateWithFallback(
  db: ReadonlyDB<DB>,
  eventType: string,
  channelDbId: string,
  locale: string,
): Promise<TemplateRow | undefined> {
  const template = await loadTemplate(db, eventType, channelDbId, locale);
  if (template || locale === DEFAULT_LOCALE) return template;
  return loadTemplate(db, eventType, channelDbId, DEFAULT_LOCALE);
}
