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

// GET /api/reports - Get all reports for the authenticated user
export async function GET(request: NextRequest) {
  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 reports = await prisma.report.findMany({
      where: {
        userId: payload.userId,
      },
      orderBy: {
        createdAt: 'desc',
      },
      select: {
        id: true,
        name: true,
        title: true,
        createdAt: true,
        updatedAt: true,
      },
    });

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

// POST /api/reports - Create a new report
export async function POST(request: NextRequest) {
  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 body = await request.json();
    
    // Validare manuală
    if (!body.name || typeof body.name !== 'string' || body.name.trim().length === 0) {
      return NextResponse.json(
        { error: 'Numele raportului este obligatoriu' },
        { status: 400 }
      );
    }
    
    if (!body.title || typeof body.title !== 'string' || body.title.trim().length === 0) {
      return NextResponse.json(
        { error: 'Titlul raportului este obligatoriu' },
        { status: 400 }
      );
    }
    
    if (!body.data || typeof body.data !== 'object') {
      return NextResponse.json(
        { error: 'Datele raportului sunt obligatorii' },
        { status: 400 }
      );
    }
    
    const { name, title, data, results } = body;

    const report = await prisma.report.create({
      data: {
        userId: payload.userId,
        name,
        title,
        data,
        results,
      },
    });

    return NextResponse.json({
      report: {
        id: report.id,
        name: report.name,
        title: report.title,
        createdAt: report.createdAt,
        updatedAt: report.updatedAt,
      },
    });
  } catch (error) {
    console.error('Error creating report:', error);
    return NextResponse.json(
      { error: 'A apărut o eroare la crearea raportului' },
      { status: 500 }
    );
  }
}
