"use server";

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

const ALLOWED_ROLES = new Set(["user", "editor", "admin"]);

async function logAudit(
  user: { id: string; name: string; email: string },
  action: string,
  target: string,
  meta: Record<string, unknown>,
) {
  await prisma.auditLog.create({
    data: {
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      source: "admin",
      action,
      target,
      meta: meta as never,
    },
  });
}

export async function changeRoleAction(userId: string, role: string) {
  const me = await requireAdmin();
  if (!ALLOWED_ROLES.has(role))
    return { ok: false as const, error: "Role không hợp lệ." };
  if (userId === me.id && role !== "admin")
    return { ok: false as const, error: "Bạn không thể tự hạ quyền của chính mình." };

  const target = await prisma.user.findUnique({ where: { id: userId } });
  if (!target) return { ok: false as const, error: "Không tìm thấy user." };

  await prisma.user.update({ where: { id: userId }, data: { role } });
  await logAudit(me, "user.change_role", userId, {
    from: target.role,
    to: role,
    email: target.email,
  });
  revalidatePath("/admin/users");
  return { ok: true as const };
}

export async function deleteUserAction(userId: string) {
  const me = await requireAdmin();
  if (userId === me.id)
    return { ok: false as const, error: "Bạn không thể xóa chính mình." };

  const target = await prisma.user.findUnique({
    where: { id: userId },
    select: { email: true, name: true, _count: { select: { articles: true } } },
  });
  if (!target) return { ok: false as const, error: "Không tìm thấy user." };

  if (target._count.articles > 0) {
    return {
      ok: false as const,
      error: `User này còn ${target._count.articles} bài. Chuyển bài cho user khác trước khi xóa.`,
    };
  }

  await prisma.user.delete({ where: { id: userId } });
  await logAudit(me, "user.delete", userId, { email: target.email, name: target.name });
  revalidatePath("/admin/users");
  return { ok: true as const };
}

export async function reassignArticlesAction(fromUserId: string, toUserId: string) {
  const me = await requireAdmin();
  const [from, to] = await Promise.all([
    prisma.user.findUnique({ where: { id: fromUserId }, select: { email: true } }),
    prisma.user.findUnique({ where: { id: toUserId }, select: { email: true } }),
  ]);
  if (!from || !to) return { ok: false as const, error: "Không tìm thấy user." };

  const result = await prisma.article.updateMany({
    where: { authorId: fromUserId },
    data: { authorId: toUserId },
  });
  await logAudit(me, "user.reassign_articles", fromUserId, {
    to: toUserId,
    count: result.count,
    fromEmail: from.email,
    toEmail: to.email,
  });
  revalidatePath("/admin/users");
  revalidatePath("/admin/articles");
  return { ok: true as const, count: result.count };
}
