import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { verifyToken } from '@/lib/auth';

// GET /api/reports/[id] - Get a specific report
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const token = request.headers.get('authorization')?.replace('Bearer ', '');
    
    if (!token) {
      return NextResponse.json(
        { error: 'Token de autentificare lipsă' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { error: 'Token invalid' },
        { status: 401 }
      );
    }

    const { id } = await params;
    const report = await prisma.report.findFirst({
      where: {
        id: id,
        userId: payload.userId, // Ensure user can only access their own reports
      },
    });

    if (!report) {
      return NextResponse.json(
        { error: 'Raportul nu a fost găsit' },
        { status: 404 }
      );
    }

    return NextResponse.json({ report });
  } catch (error) {
    console.error('Error fetching report:', error);
    return NextResponse.json(
      { error: 'A apărut o eroare la încărcarea raportului' },
      { status: 500 }
    );
  }
}

// DELETE /api/reports/[id] - Delete a specific report
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const token = request.headers.get('authorization')?.replace('Bearer ', '');
    
    if (!token) {
      return NextResponse.json(
        { error: 'Token de autentificare lipsă' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { error: 'Token invalid' },
        { status: 401 }
      );
    }

    const { id } = await params;
    const report = await prisma.report.findFirst({
      where: {
        id: id,
        userId: payload.userId, // Ensure user can only delete their own reports
      },
    });

    if (!report) {
      return NextResponse.json(
        { error: 'Raportul nu a fost găsit' },
        { status: 404 }
      );
    }

    await prisma.report.delete({
      where: {
        id: id,
      },
    });

    return NextResponse.json({ message: 'Raportul a fost șters cu succes' });
  } catch (error) {
    console.error('Error deleting report:', error);
    return NextResponse.json(
      { error: 'A apărut o eroare la ștergerea raportului' },
      { status: 500 }
    );
  }
}
