import { count, list, type Comment, type CommentAuthor, type CommentTarget, type CommentsSchema } from '@platform-modules/comments';
import type { Querier } from '@platform-modules/db';
import { safeAuthorUrl } from './comments.js';

const PUBLIC_COMMENT_LIMIT = 100;
const MAX_VISUAL_DEPTH = 5;

export function escapeHtml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

/** F1/F2 — safe author label + optional http(s) href; email never exposed. */
export function guestAuthorParts(author: CommentAuthor): { label: string; href: string | null } {
  if (author.kind === 'user') {
    return { label: 'Member', href: null };
  }
  return {
    label: author.name,
    href: author.url ? safeAuthorUrl(author.url) : null,
  };
}

export function commentIndentStyle(depth: number): string {
  const capped = Math.min(depth, MAX_VISUAL_DEPTH);
  return capped > 0 ? `margin-inline-start: ${capped * 1.5}rem` : '';
}

export async function loadPublicComments(
  db: Querier<CommentsSchema>,
  target: CommentTarget,
): Promise<{ total: number; comments: Comment[] }> {
  const [total, page] = await Promise.all([
    count(db, target),
    list(db, target, { order: 'oldest', limit: PUBLIC_COMMENT_LIMIT }, undefined),
  ]);
  return { total, comments: page.items };
}

export { PUBLIC_COMMENT_LIMIT, MAX_VISUAL_DEPTH };
