import { NextRequest, NextResponse } from 'next/server';
import prisma from '../../../../../lib/prisma';

export async function GET(
    request: NextRequest,
    { params }: { params: Promise<{ id: string }> }
) {
    try {
        const { id } = await params;

        if (!id) {
            return NextResponse.json({ error: 'ID Business requis' }, { status: 400 });
        }

        // 1. Get total views from AnalyticsEvent
        const totalViews = await prisma.analyticsEvent.count({
            where: {
                type: 'BUSINESS_VIEW',
                metadata: {
                    path: ['businessId'],
                    equals: id
                }
            }
        });

        // 2. Get contact clicks from AnalyticsEvent
        const contactClicks = await prisma.analyticsEvent.count({
            where: {
                type: 'BUSINESS_CONTACT_CLICK',
                metadata: {
                    path: ['businessId'],
                    equals: id
                }
            }
        });

        // 3. Get monthly stats (views per day for last 30 days)
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

        // Note: Raw query might be needed for group by date in some DBs, 
        // but for now we'll just return the totals for simplicity.
        
        return NextResponse.json({
            businessId: id,
            totalViews,
            contactClicks,
            updatedAt: new Date().toISOString()
        });

    } catch (error) {
        console.error('Error fetching business analytics:', error);
        return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 });
    }
}
