import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "../../auth/authOptions";
import { prisma } from "@/lib/prisma";

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions);
  if (!session) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  try {
    const resolvedParams = await params;
    const communicationId = parseInt(resolvedParams.id);
    
    const communication = await prisma.communication.findUnique({
      where: { id: communicationId },
      include: {
        client: true,
        folder: true,
        documents: true,
      }
    });

    if (!communication) {
      return NextResponse.json({ error: "Communication non trouvée" }, { status: 404 });
    }

    return NextResponse.json(communication);
  } catch (error) {
    console.error('Erreur lors de la récupération de la communication:', error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}

export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions);
  if (!session) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  try {
    const resolvedParams = await params;
    const communicationId = parseInt(resolvedParams.id);
    const data = await req.json();
    
    const communication = await prisma.communication.update({
      where: { id: communicationId },
      data,
      include: {
        client: true,
        folder: true,
        documents: true,
      }
    });

    return NextResponse.json(communication);
  } catch (error) {
    console.error('Erreur lors de la mise à jour de la communication:', error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}

export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions);
  if (!session) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  try {
    const resolvedParams = await params;
    const communicationId = parseInt(resolvedParams.id);
    
    await prisma.communication.delete({
      where: { id: communicationId }
    });

    return NextResponse.json({ message: "Communication supprimée" });
  } catch (error) {
    console.error('Erreur lors de la suppression de la communication:', error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}
