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) {
  const session = await getServerSession(authOptions);
  if (!session) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  try {
    const { searchParams } = new URL(req.url);
    const clientId = searchParams.get('clientId');
    const folderId = searchParams.get('folderId');

    let whereClause: any = {};

    if (clientId) {
      whereClause.clientId = parseInt(clientId);
    }

    if (folderId) {
      whereClause.folderId = parseInt(folderId);
    }

    const communications = await prisma.communication.findMany({
      where: whereClause,
      include: {
        client: true,
        folder: true,
      },
      orderBy: { createdAt: 'desc' }
    });

    return NextResponse.json(communications);
  } catch (error) {
    console.error('Erreur lors de la récupération des communications:', error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  const session = await getServerSession(authOptions);
  if (!session) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  try {
    const data = await req.json();
    
    const communication = await prisma.communication.create({
      data: {
        ...data,
        userId: parseInt(session.user.id)
      },
      include: {
        client: true,
        folder: true,
      }
    });

    return NextResponse.json(communication, { status: 201 });
  } catch (error) {
    console.error('Erreur lors de la création de la communication:', error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}
