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

type ChannelOrderByField = "createdAt" | "channelId" | "displayName";

export interface ListNotificationChannelsInput extends PaginationInput<ChannelOrderByField> {
  enabledOnly?: boolean;
}

/**
 * Returns the NotificationChannel registry as a paginated result, optionally filtered to enabled channels.
 */
export async function run(db: ReadonlyDB<DB>, input: ListNotificationChannelsInput) {
  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("NotificationChannel").selectAll();

  if (input.enabledOnly === true) {
    query = query.where("enabled", "=", true);
  }

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

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