import { cache } from "react";
import { auth } from "@/auth";
import { prisma } from "@/lib/db";
import { canAccessEvaluation } from "@/lib/evaluation-access";

export async function getEvaluations(options?: { status?: string; templateId?: string }) {
  const session = await auth();
  if (!session?.user) return null;

  const isAdmin = session.user.role === "admin";
  const userId = session.user.id;

  const evaluations = await prisma.evaluation.findMany({
    where: {
      ...(options?.status && { status: options.status }),
      ...(options?.templateId && { templateId: options.templateId }),
      ...(!isAdmin && {
        OR: [
          { evaluatorId: userId },
          { sharedWith: { some: { userId } } },
          { isPublic: true },
        ],
      }),
    },
    include: {
      template: { include: { dimensions: { orderBy: { orderIndex: "asc" } } } },
      dimensionScores: { include: { dimension: true } },
    },
    orderBy: { evaluationDate: "desc" },
  });

  return evaluations.map((e) => ({
    ...e,
    evaluationDate: e.evaluationDate.toISOString(),
  }));
}

export async function getEvaluation(id: string) {
  const session = await auth();
  if (!session?.user) return null;

  const evaluation = await prisma.evaluation.findUnique({
    where: { id },
    include: {
      template: {
        include: {
          dimensions: { orderBy: { orderIndex: "asc" } },
        },
      },
      dimensionScores: { include: { dimension: true } },
      sharedWith: { include: { user: { select: { id: true, email: true, name: true } } } },
    },
  });

  if (!evaluation) return null;

  const hasAccess = await canAccessEvaluation(
    id,
    session.user.id,
    session.user.role === "admin",
    true
  );
  if (!hasAccess) return null;

  return {
    ...evaluation,
    evaluationDate: evaluation.evaluationDate.toISOString(),
  };
}

export const getTemplates = cache(async () => {
  const templates = await prisma.template.findMany({
    include: {
      dimensions: { orderBy: { orderIndex: "asc" } },
    },
    orderBy: { id: "desc" },
  });
  return templates;
});

export async function getUsers() {
  const session = await auth();
  if (!session?.user) return null;
  return prisma.user.findMany({
    orderBy: { email: "asc" },
    select: { id: true, email: true, name: true },
  });
}

export async function getAdminUsers() {
  const session = await auth();
  if (session?.user?.role !== "admin") return null;
  const users = await prisma.user.findMany({
    orderBy: { createdAt: "desc" },
    select: { id: true, email: true, name: true, role: true, createdAt: true },
  });
  return users.map((u) => ({ ...u, createdAt: u.createdAt.toISOString() }));
}
