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 limit = searchParams.get('limit') || '50';

    let whereClause: any = {};

    if (clientId) {
      whereClause.clientId = parseInt(clientId);
    }

    const activityLogs = await prisma.activityLog.findMany({
      where: whereClause,
      include: {
        client: true,
        communication: true,
        partner: true,
        task: true,
      },
      orderBy: { createdAt: 'desc' },
      take: parseInt(limit)
    });

    return NextResponse.json(activityLogs);
  } catch (error) {
    console.error('Erreur lors de la récupération des logs d\'activité:', 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 { action, description, entityType, entityId, clientId, folderId } = await req.json();

    const activityLog = await prisma.activityLog.create({
      data: {
        action,
        description,
        entityType,
        entityId,
        clientId: clientId ? parseInt(clientId) : null,
        folderId: folderId ? parseInt(folderId) : null,
        userId: parseInt(session.user.id),
      },
      include: {
        client: true,
        communication: true,
        partner: true,
        task: true,
      }
    });

    return NextResponse.json(activityLog, { status: 201 });
  } catch (error) {
    console.error('Erreur lors de la création du log d\'activité:', error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
} 