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

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

    const body = await req.json();
    const { bundleId, locations } = body;

    if (!bundleId || !locations || locations.length === 0) {
      return NextResponse.json(
        { error: 'Bundle ID and locations are required' },
        { status: 400 }
      );
    }

    // Simple optimization: nearest neighbor algorithm
    // In production, use a proper routing API like Google Maps Directions or OR-Tools
    const optimizedRoute = locations; // Placeholder
    const totalDistance = locations.length * 15; // Placeholder: ~15km between each
    const estimatedTime = locations.length * 1.5; // Placeholder: ~1.5 hours per job

    // Update bundle with optimized route
    const bundle = await prisma.jobBundle.update({
      where: { id: bundleId },
      data: {
        optimizedRoute: { route: optimizedRoute },
        totalDistance,
        estimatedTime,
      },
    });

    return NextResponse.json({
      bundle,
      optimizedRoute,
      totalDistance,
      estimatedTime,
      message: 'Route optimized successfully',
    });
  } catch (error) {
    console.error('Error optimizing route:', error);
    return NextResponse.json(
      { error: 'Failed to optimize route' },
      { status: 500 }
    );
  }
}
