"use server";

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

export type RobotsRule = {
  userAgent: string;
  allow: string[];
  disallow: string[];
  crawlDelay?: number | null;
};

export type RobotsConfig = {
  rules: RobotsRule[];
  host: string;
};

const DEFAULT_RULES: RobotsRule[] = [
  {
    userAgent: "*",
    allow: ["/"],
    disallow: ["/api/", "/admin", "/admin/", "/login"],
    crawlDelay: null,
  },
];

export async function loadRobotsConfig(): Promise<RobotsConfig> {
  const [rulesRow, hostRow] = await Promise.all([
    prisma.setting.findUnique({ where: { key: "seo.robots_rules" } }),
    prisma.setting.findUnique({ where: { key: "seo.robots_host" } }),
  ]);

  let rules = DEFAULT_RULES;
  if (rulesRow?.value) {
    try {
      const parsed = JSON.parse(rulesRow.value);
      if (Array.isArray(parsed) && parsed.length > 0) {
        rules = parsed.map((r) => ({
          userAgent: String(r.userAgent ?? "*"),
          allow: Array.isArray(r.allow)
            ? r.allow
            : typeof r.allow === "string"
              ? [r.allow]
              : [],
          disallow: Array.isArray(r.disallow)
            ? r.disallow
            : typeof r.disallow === "string"
              ? [r.disallow]
              : [],
          crawlDelay: typeof r.crawlDelay === "number" ? r.crawlDelay : null,
        }));
      }
    } catch {
      // fall through to defaults
    }
  }

  return {
    rules,
    host: hostRow?.value || (process.env.NEXT_PUBLIC_SITE_URL ?? "https://v2.finzone.io.vn"),
  };
}

export async function saveRobotsConfig(formData: FormData): Promise<{
  ok: boolean;
  error?: string;
}> {
  const user = await requireAdmin();
  const raw = String(formData.get("rules") ?? "");
  const host = String(formData.get("host") ?? "").trim();

  let parsed: RobotsRule[];
  try {
    parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) throw new Error("phải là array");
    for (const r of parsed) {
      if (!r.userAgent) throw new Error("mỗi rule cần userAgent");
    }
  } catch (e) {
    return {
      ok: false,
      error: `JSON không hợp lệ: ${e instanceof Error ? e.message : "unknown"}`,
    };
  }

  await prisma.setting.upsert({
    where: { key: "seo.robots_rules" },
    create: { key: "seo.robots_rules", value: JSON.stringify(parsed) },
    update: { value: JSON.stringify(parsed) },
  });

  if (host) {
    await prisma.setting.upsert({
      where: { key: "seo.robots_host" },
      create: { key: "seo.robots_host", value: host },
      update: { value: host },
    });
  }

  await prisma.auditLog.create({
    data: {
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      source: "admin",
      action: "robots.update",
      target: "robots.txt",
      meta: { rules: parsed.length, host } as never,
    },
  });

  revalidatePath("/robots.txt");
  revalidatePath("/admin/super-seo/robots");
  return { ok: true };
}

export async function resetRobotsConfig(): Promise<{ ok: boolean }> {
  const user = await requireAdmin();
  await prisma.setting.deleteMany({
    where: { key: { in: ["seo.robots_rules", "seo.robots_host"] } },
  });
  await prisma.auditLog.create({
    data: {
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      source: "admin",
      action: "robots.reset",
      target: "robots.txt",
      meta: {} as never,
    },
  });
  revalidatePath("/robots.txt");
  revalidatePath("/admin/super-seo/robots");
  return { ok: true };
}
