import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/authOptions";
import { prisma } from "@/lib/prisma";
import { NotificationType } from "@prisma/client";

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
    }

    const { searchParams } = new URL(req.url);
    const limit = searchParams.get('limit');
    const limitNumber = limit ? parseInt(limit) : 50;

    const notifications = await prisma.notification.findMany({
      where: { 
        userId: parseInt(session.user.id)
      },
      orderBy: { createdAt: 'desc' },
      take: limitNumber
    });

    return NextResponse.json(notifications);
  } catch (error) {
    console.error('Erreur lors de la récupération des notifications:', error);
    return NextResponse.json(
      { error: "Erreur lors de la récupération des notifications" },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
    }

    const { userId, type, content, relatedType, relatedId } = await req.json();

    if (!userId || !type || !content) {
      return NextResponse.json({ error: "Données manquantes" }, { status: 400 });
    }

    const notification = await prisma.notification.create({
      data: {
        userId: parseInt(userId),
        type: type as NotificationType,
        content,
        relatedType,
        relatedId,
        isRead: false
      }
    });

    return NextResponse.json({ success: true, notification });
  } catch (error) {
    console.error('Erreur lors de la création de la notification:', error);
    return NextResponse.json(
      { error: "Erreur lors de la création de la notification" },
      { status: 500 }
    );
  }
}

export async function PUT(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
    }

    const { notificationId } = await req.json();

    if (!notificationId) {
      return NextResponse.json({ error: "ID de notification requis" }, { status: 400 });
    }

    await prisma.notification.update({
      where: { 
        id: parseInt(notificationId),
        userId: parseInt(session.user.id) 
      },
      data: { isRead: true }
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Erreur lors de la mise à jour de la notification:', error);
    return NextResponse.json(
      { error: "Erreur lors de la mise à jour de la notification" },
      { status: 500 }
    );
  }
} 