"use server";

import { prisma } from "@/lib/db";
import { requireAuth, requireEvaluationAccess, type ActionResult } from "@/lib/action-helpers";
import { revalidatePath } from "next/cache";


export async function addShare(evaluationId: string, userId: string): Promise<ActionResult> {
  const session = await requireAuth();
  if (!session) return { success: false, error: "Non authentifié" };

  const hasAccess = await requireEvaluationAccess(evaluationId, session.user.id, session.user.role === "admin");
  if (!hasAccess) return { success: false, error: "Accès refusé" };

  if (userId === session.user.id) return { success: false, error: "Vous avez déjà accès" };

  const evaluation = await prisma.evaluation.findUnique({
    where: { id: evaluationId },
    select: { evaluatorId: true },
  });
  if (evaluation?.evaluatorId === userId) {
    return { success: false, error: "L'évaluateur a déjà accès" };
  }

  try {
    await prisma.evaluationShare.upsert({
      where: { evaluationId_userId: { evaluationId, userId } },
      create: { evaluationId, userId },
      update: {},
    });
    revalidatePath(`/evaluations/${evaluationId}`);
    return { success: true };
  } catch (e) {
    console.error(e);
    return { success: false, error: "Erreur" };
  }
}

export async function removeShare(evaluationId: string, userId: string): Promise<ActionResult> {
  const session = await requireAuth();
  if (!session) return { success: false, error: "Non authentifié" };

  const hasAccess = await requireEvaluationAccess(evaluationId, session.user.id, session.user.role === "admin");
  if (!hasAccess) return { success: false, error: "Accès refusé" };

  try {
    await prisma.evaluationShare.deleteMany({
      where: { evaluationId, userId },
    });
    revalidatePath(`/evaluations/${evaluationId}`);
    return { success: true };
  } catch (e) {
    console.error(e);
    return { success: false, error: "Erreur" };
  }
}
