// app/api/users/[userId]/conversations/route.ts
import { NextResponse } from "next/server";
;
import { prisma } from '@/lib/prisma';

export async function GET(
    req: Request,
    { params }: { params: Promise<{ userId: string }> }
) {
    const {userId}= await params;
    try {
        const { searchParams } = new URL(req.url);
        const page = parseInt(searchParams.get("page") || "1");
        const limit = parseInt(searchParams.get("limit") || "10");
        const skip = (page - 1) * limit;
        
        const [conversations, total] = await Promise.all([
            prisma.conversation.findMany({
                where: { telegramUserId: userId },
                skip,
                take: limit,
                orderBy: { createdAt: "desc" },
                include: {
                    _count: {
                        select: { messages: true }
                    },
                    messages: {
                        orderBy: { createdAt: "asc" },
                    }
                }
            }),
            prisma.conversation.count({
                where: { telegramUserId: userId }
            })
        ]);
        
        return NextResponse.json({
            conversations,
            meta: {
                total,
                page,
                limit,
                pages: Math.ceil(total / limit)
            }
        });
    } catch (error) {
        console.error("[USER_CONVERSATIONS_GET]", error);
        return NextResponse.json({ error: "Internal server error" }, { status: 500 });
    }
}