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

type AuditOrderByField = "occurredAt" | "createdAt";

export interface ListAuditByNotificationInput extends PaginationInput<AuditOrderByField> {
  notificationId: string;
}

/**
 * Returns the paginated audit trail for a Notification ordered by occurredAt, scoped to the recipient.
 */
export async function run(
  db: ReadonlyDB<DB>,
  input: ListAuditByNotificationInput,
  ctx: QueryContext,
) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "occurredAt";
  const orderDirection = input.orderDirection ?? "asc";

  // Self-scope: a caller may only read the audit trail of notifications
  // addressed to them. Missing and other-recipient notifications both come
  // back as an empty page so existence cannot be probed.
  const parent = await db
    .selectFrom("Notification")
    .select(["recipientUserId"])
    .where("id", "=", input.notificationId)
    .executeTakeFirst();

  if (!parent || parent.recipientUserId !== ctx.actorId) {
    return ok(buildPaginatedResult([], limit));
  }

  const rows = await db
    .selectFrom("NotificationDeliveryAudit")
    .selectAll()
    .where("notificationId", "=", input.notificationId)
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

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