"use server";

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

export async function resolveAction(id: string): Promise<{ ok: boolean; error?: string }> {
  await requireAdmin();
  await prisma.notFoundLog.update({ where: { id }, data: { resolved: true } });
  revalidatePath("/admin/super-seo/404-monitor");
  return { ok: true };
}

export async function deleteAction(id: string): Promise<{ ok: boolean; error?: string }> {
  await requireAdmin();
  await prisma.notFoundLog.delete({ where: { id } });
  revalidatePath("/admin/super-seo/404-monitor");
  return { ok: true };
}

export async function autoCreateRedirectAction(input: {
  fromPath: string;
  toPath: string;
  statusCode?: number;
}): Promise<{ ok: boolean; error?: string }> {
  await requireAdmin();
  const { fromPath, toPath, statusCode = 301 } = input;
  if (!fromPath || !toPath) return { ok: false, error: "Thiếu path." };
  if (fromPath === toPath) return { ok: false, error: "From và to trùng nhau." };

  // Upsert redirect
  await prisma.redirect.upsert({
    where: { fromPath },
    create: { fromPath, toPath, statusCode },
    update: { toPath, statusCode, enabled: true },
  });

  // Mark all 404 logs for this path resolved
  await prisma.notFoundLog.updateMany({
    where: { path: fromPath },
    data: { resolved: true },
  });

  revalidatePath("/admin/super-seo/404-monitor");
  revalidatePath("/admin/super-seo/redirects");
  return { ok: true };
}
