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

export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { reportType, filters, dateRange } = await request.json();

    let data = [];

    switch (reportType) {
      case 'quotes':
        data = await prisma.quote.findMany({
          where: {
            ...(filters?.status && { status: filters.status }),
            ...(dateRange && {
              createdAt: {
                gte: new Date(dateRange.from),
                lte: new Date(dateRange.to),
              },
            }),
          },
          orderBy: { createdAt: 'desc' },
        });
        break;

      case 'leads':
        data = await prisma.lead.findMany({
          where: {
            ...(filters?.status && { status: filters.status }),
            ...(dateRange && {
              createdAt: {
                gte: new Date(dateRange.from),
                lte: new Date(dateRange.to),
              },
            }),
          },
          orderBy: { createdAt: 'desc' },
        });
        break;

      case 'contracts':
        data = await prisma.contract.findMany({
          where: {
            ...(filters?.status && { status: filters.status }),
            ...(dateRange && {
              createdAt: {
                gte: new Date(dateRange.from),
                lte: new Date(dateRange.to),
              },
            }),
          },
          orderBy: { createdAt: 'desc' },
        });
        break;

      case 'revenue':
        data = await prisma.quote.findMany({
          where: {
            status: 'ACCEPTED',
            ...(dateRange && {
              acceptedAt: {
                gte: new Date(dateRange.from),
                lte: new Date(dateRange.to),
              },
            }),
          },
          select: {
            quoteNumber: true,
            total: true,
            acceptedAt: true,
            services: true,
          },
        });
        break;

      default:
        return NextResponse.json({ error: 'Invalid report type' }, { status: 400 });
    }

    return NextResponse.json({ data, count: data.length });
  } catch (error) {
    console.error('Error generating custom report:', error);
    return NextResponse.json(
      { error: 'Failed to generate report' },
      { status: 500 }
    );
  }
}
