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

export async function POST(request: NextRequest) {
  try {
    const urlParts = request.url.split('/');
    const apiIndex = urlParts.indexOf('api');
    // The id is after /api/reports/
    const id = urlParts[apiIndex + 2]; // reports/[id]/upvote

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'Report ID is required' },
        { status: 400 }
      );
    }

    const report = await db.scamReport.findUnique({
      where: { id },
    });

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

    const updatedReport = await db.scamReport.update({
      where: { id },
      data: { upvotes: { increment: 1 } },
    });

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