"use server";

import { revalidatePath } from "next/cache";
import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/admin-guard";
import { analyzeArticle } from "@/lib/seo/analyzer";
import { readabilityScore } from "@/lib/seo-engine";

export type BulkReanalyzeResult = {
  ok: boolean;
  scanned: number;
  updated: number;
  improved: number;
  worsened: number;
  unchanged: number;
  avgBefore: number;
  avgAfter: number;
  error?: string;
};

/**
 * Re-run the analyzer on every article (regardless of status) and persist
 * fresh `seoScore` / `seoChecks` / `readabilityScore`. Useful after porting
 * legacy content (WP import) or after upgrading the analyzer.
 */
export async function bulkReanalyzeAction(opts?: {
  publishedOnly?: boolean;
}): Promise<BulkReanalyzeResult> {
  const user = await requireAdmin();

  const where = opts?.publishedOnly ? { status: "published" as const } : {};
  const articles = await prisma.article.findMany({
    where,
    select: {
      id: true,
      title: true,
      slug: true,
      content: true,
      coverImage: true,
      metaTitle: true,
      metaDesc: true,
      focusKeyword: true,
      metaKeywords: true,
      seoScore: true,
    },
  });

  let updated = 0;
  let improved = 0;
  let worsened = 0;
  let unchanged = 0;
  let sumBefore = 0;
  let sumAfter = 0;

  for (const a of articles) {
    const before = a.seoScore ?? 0;
    const report = analyzeArticle({
      title: a.title,
      metaTitle: a.metaTitle,
      slug: a.slug,
      metaDesc: a.metaDesc,
      focusKeyword: a.focusKeyword,
      metaKeywords: a.metaKeywords,
      content: a.content,
      coverImage: a.coverImage,
    });
    const readability = readabilityScore(a.content);
    const after = report.score;

    sumBefore += before;
    sumAfter += after;

    if (after > before) improved++;
    else if (after < before) worsened++;
    else unchanged++;

    await prisma.article.update({
      where: { id: a.id },
      data: {
        seoScore: after,
        readabilityScore: readability,
        seoChecks: {
          grade: report.grade,
          checks: report.checks,
          stats: report.stats,
        } as never,
      },
    });
    updated++;
  }

  await prisma.auditLog.create({
    data: {
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      source: "admin",
      action: "seo.bulk_reanalyze",
      target: "",
      meta: {
        scanned: articles.length,
        updated,
        improved,
        worsened,
        unchanged,
        avgBefore: articles.length ? +(sumBefore / articles.length).toFixed(1) : 0,
        avgAfter: articles.length ? +(sumAfter / articles.length).toFixed(1) : 0,
        publishedOnly: !!opts?.publishedOnly,
      } as never,
    },
  });

  revalidatePath("/admin/super-seo/health");
  revalidatePath("/admin/articles");

  return {
    ok: true,
    scanned: articles.length,
    updated,
    improved,
    worsened,
    unchanged,
    avgBefore: articles.length ? +(sumBefore / articles.length).toFixed(1) : 0,
    avgAfter: articles.length ? +(sumAfter / articles.length).toFixed(1) : 0,
  };
}
