import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const id = request.url.split('/').filter(Boolean).pop();
    if (!id) {
      return NextResponse.json(
        { success: false, error: 'Report ID is required' },
        { status: 400 }
      );
    }

    // Don't increment views for upvote sub-routes
    const urlPath = new URL(request.url).pathname;
    const isUpvoteRoute = urlPath.includes('/upvote');

    const report = await db.scamReport.findUnique({
      where: { id },
      include: {
        reporter: {
          select: { id: true, name: true, email: true },
        },
        category: true,
        evidence: true,
        linkedEntities: true,
      },
    });

    if (!report) {
      return NextResponse.json(
        { success: false, error: 'Report not found' },
        { status: 404 }
      );
    }

    // Increment view count only for direct report detail view
    if (!isUpvoteRoute) {
      await db.scamReport.update({
        where: { id },
        data: { views: { increment: 1 } },
      });
    }

    return NextResponse.json(
      { success: true, data: report },
      { status: 200 }
    );
  } catch (error) {
    console.error('Get report error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}
