// src/lib/pages/issues.ts — calcul des issues on-page (pur, aucune DB).

import { normalizePageUrl } from "./mapping";
import type { CrawledPage } from "./types";

const TITLE_LONG = 60;
const TITLE_SHORT = 15;
const DESC_LONG = 160;
const DESC_SHORT = 50;

/**
 * Issues on-page selon les bornes exactes de la spec. Une page saine → `[]`.
 * Ordre déterministe : title, description, h1, noindex, canonical, error.
 */
export function computeIssues(p: CrawledPage): string[] {
  const issues: string[] = [];

  const title = p.title?.trim() ?? "";
  if (!title) issues.push("title-missing");
  else {
    if (title.length > TITLE_LONG) issues.push("title-long");
    if (title.length < TITLE_SHORT) issues.push("title-short");
  }

  const desc = p.metaDescription?.trim() ?? "";
  if (!desc) issues.push("description-missing");
  else {
    if (desc.length > DESC_LONG) issues.push("description-long");
    if (desc.length < DESC_SHORT) issues.push("description-short");
  }

  if (!(p.h1?.trim() ?? "")) issues.push("h1-missing");
  if (p.h1Count > 1) issues.push("h1-multiple");

  if (p.robots?.toLowerCase().includes("noindex")) issues.push("noindex");

  const canonical = p.canonical?.trim() ?? "";
  if (canonical && normalizePageUrl(canonical) !== normalizePageUrl(p.url)) {
    issues.push("canonical-mismatch");
  }

  if (p.status >= 400 || p.status === 0) issues.push("error");

  return issues;
}
