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

// GET /api/bundles - Get job bundles
export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const user = await prisma.user.findUnique({
      where: { email: session.user.email },
    });

    if (!user) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    const { searchParams } = new URL(req.url);
    const contractorId = searchParams.get('contractorId') || user.id;

    const bundles = await prisma.jobBundle.findMany({
      where: {
        contractorId: user.role === 'ADMIN' ? undefined : contractorId,
      },
      orderBy: { createdAt: 'desc' },
    });

    return NextResponse.json({ bundles });
  } catch (error) {
    console.error('Error fetching job bundles:', error);
    return NextResponse.json(
      { error: 'Failed to fetch job bundles' },
      { status: 500 }
    );
  }
}

// POST /api/bundles - Create job bundle
export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const user = await prisma.user.findUnique({
      where: { email: session.user.email },
    });

    if (!user) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    const body = await req.json();
    const {
      name,
      contractorId,
      contractIds,
      totalValue,
      discountAmount,
      status,
      startDate,
      endDate,
    } = body;

    if (!contractIds || contractIds.length === 0) {
      return NextResponse.json(
        { error: 'At least one contract is required' },
        { status: 400 }
      );
    }

    const bundle = await prisma.jobBundle.create({
      data: {
        name,
        contractorId: contractorId || user.id,
        contractIds,
        totalValue,
        discountAmount: discountAmount || 0,
        finalAmount: totalValue - (discountAmount || 0),
        status: status || 'DRAFT',
        startDate: startDate ? new Date(startDate) : undefined,
        endDate: endDate ? new Date(endDate) : undefined,
      },
    });

    return NextResponse.json({ bundle }, { status: 201 });
  } catch (error) {
    console.error('Error creating job bundle:', error);
    return NextResponse.json(
      { error: 'Failed to create job bundle' },
      { status: 500 }
    );
  }
}
