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

type TemplateOrderByField = "createdAt" | "eventType" | "channelId" | "locale";

export interface ListNotificationTemplatesInput extends PaginationInput<TemplateOrderByField> {
  eventType?: string;
  channelId?: string;
  locale?: string;
}

/**
 * Returns NotificationTemplates as a paginated result, optionally filtered by eventType, channelId, and/or locale.
 */
export async function run(db: ReadonlyDB<DB>, input: ListNotificationTemplatesInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "createdAt";
  const orderDirection = input.orderDirection ?? "desc";

  let query = db.selectFrom("NotificationTemplate").selectAll();

  if (input.eventType) {
    query = query.where("eventType", "=", input.eventType);
  }
  if (input.channelId) {
    query = query.where("channelId", "=", input.channelId);
  }
  if (input.locale) {
    query = query.where("locale", "=", input.locale);
  }

  const templates = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

  return ok(buildPaginatedResult(templates, limit));
}
