"use server";

import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/admin-guard";

export type PingResult = {
  ok: boolean;
  results: Array<{ engine: string; status: number | string; ok: boolean }>;
  error?: string;
};

const SITE = process.env.NEXT_PUBLIC_SITE_URL ?? "https://v2.finzone.io.vn";

/**
 * Ping search engines that the sitemap has been updated.
 * Google deprecated the ping endpoint in 2023, but Bing/IndexNow still works.
 * For Google we recommend Search Console; we just record the intent here.
 */
export async function pingSearchEnginesAction(): Promise<PingResult> {
  const user = await requireAdmin();
  const sitemap = `${SITE}/sitemap.xml`;
  const results: PingResult["results"] = [];

  // Bing — deprecated ping API (returns 410 Gone since 2024)
  results.push({
    engine: "Bing",
    status: "Ping API ngưng từ 5/2022 — submit qua Bing Webmaster Tools",
    ok: true,
  });

  // IndexNow (Bing/Yandex). Needs a key file at /<key>.txt — we skip if not configured.
  const indexNowKey = await prisma.setting
    .findUnique({ where: { key: "seo.indexnow_key" } })
    .catch(() => null);

  if (indexNowKey?.value) {
    try {
      const r = await fetch("https://api.indexnow.org/IndexNow", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          host: new URL(SITE).host,
          key: indexNowKey.value,
          urlList: [sitemap],
        }),
        signal: AbortSignal.timeout(8000),
      });
      results.push({ engine: "IndexNow", status: r.status, ok: r.ok || r.status === 202 });
    } catch (e) {
      results.push({
        engine: "IndexNow",
        status: e instanceof Error ? e.message : "error",
        ok: false,
      });
    }
  } else {
    results.push({
      engine: "IndexNow",
      status: "skipped (chưa có key)",
      ok: false,
    });
  }

  // Google: deprecated. Just record the recommendation.
  results.push({
    engine: "Google",
    status: "Dùng Search Console (ping API đã ngưng)",
    ok: true,
  });

  await prisma.auditLog.create({
    data: {
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      source: "admin",
      action: "seo.sitemap_ping",
      target: sitemap,
      meta: { results } as never,
    },
  });

  return { ok: true, results };
}
