"use server";

import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { prisma } from "@/services/database";
import { Role } from "@/prisma/generated/prisma/client";
import { NotFoundError } from "@/services/errors";

function checkAdminAccess() {
  return async () => {
    const session = await auth();
    if (!session?.user || session.user.role !== Role.ADMIN) {
      throw new Error("Accès refusé");
    }
    return session;
  };
}

export async function addFeedbackBonusPoints(
  userId: string,
  points: number
) {
  try {
    await checkAdminAccess()();

    // Vérifier que l'utilisateur existe
    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: { id: true, score: true },
    });

    if (!user) {
      throw new NotFoundError("Utilisateur");
    }

    // Ajouter les points
    const updatedUser = await prisma.user.update({
      where: { id: userId },
      data: {
        score: {
          increment: points,
        },
      },
      select: {
        id: true,
        username: true,
        score: true,
      },
    });

    revalidatePath("/admin");
    revalidatePath("/leaderboard");

    return {
      success: true,
      message: `${points} points ajoutés avec succès`,
      data: updatedUser,
    };
  } catch (error) {
    console.error("Error adding bonus points:", error);

    if (error instanceof NotFoundError) {
      return { success: false, error: error.message };
    }
    if (error instanceof Error && error.message === "Accès refusé") {
      return { success: false, error: "Accès refusé" };
    }

    return {
      success: false,
      error: "Erreur lors de l'ajout des points",
    };
  }
}

export async function markFeedbackAsRead(feedbackId: string, isRead: boolean) {
  try {
    await checkAdminAccess()();

    // Vérifier que le feedback existe
    const feedback = await prisma.eventFeedback.findUnique({
      where: { id: feedbackId },
      select: { id: true },
    });

    if (!feedback) {
      throw new NotFoundError("Feedback");
    }

    // Mettre à jour le statut
    const updatedFeedback = await prisma.eventFeedback.update({
      where: { id: feedbackId },
      data: {
        isRead,
      },
      select: {
        id: true,
        isRead: true,
      },
    });

    revalidatePath("/admin");

    return {
      success: true,
      message: isRead
        ? "Feedback marqué comme lu"
        : "Feedback marqué comme non lu",
      data: updatedFeedback,
    };
  } catch (error) {
    console.error("Error marking feedback as read:", error);

    if (error instanceof NotFoundError) {
      return { success: false, error: error.message };
    }
    if (error instanceof Error && error.message === "Accès refusé") {
      return { success: false, error: "Accès refusé" };
    }

    return {
      success: false,
      error: "Erreur lors de la mise à jour du feedback",
    };
  }
}

