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

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

    const body = await request.json();
    const {
      contractId,
      latitude,
      longitude,
      accuracy,
      speed,
      heading,
      deviceId,
      batteryLevel,
    } = body;

    // Calculate if contractor is on-site
    const contract = await prisma.contract.findUnique({
      where: { id: contractId },
      include: {
        quote: {
          include: {
            lead: true,
          },
        },
      },
    });

    let isOnSite = false;
    let distanceToSite = null;

    if (contract?.quote.lead.latitude && contract?.quote.lead.longitude) {
      distanceToSite = calculateHaversineDistance(
        latitude,
        longitude,
        contract.quote.lead.latitude,
        contract.quote.lead.longitude
      );
      isOnSite = distanceToSite < 100; // Within 100 meters
    }

    const tracking = await prisma.vehicleTracking.create({
      data: {
        contractorId: session.user.id,
        contractId,
        latitude,
        longitude,
        accuracy,
        speed,
        heading,
        deviceId,
        batteryLevel,
        timestamp: new Date(),
        isOnSite,
        distanceToSite,
      },
    });

    return NextResponse.json({
      success: true,
      tracking,
      isOnSite,
      distanceToSite,
    });
  } catch (error) {
    console.error('Error logging vehicle tracking:', error);
    return NextResponse.json(
      { error: 'Failed to log tracking' },
      { status: 500 }
    );
  }
}

// GET /api/tracking/vehicle?contractId=xxx - Get vehicle location history
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const contractId = searchParams.get('contractId');
    const hours = parseInt(searchParams.get('hours') || '24');

    if (!contractId) {
      return NextResponse.json({ error: 'Contract ID required' }, { status: 400 });
    }

    const since = new Date(Date.now() - hours * 60 * 60 * 1000);

    const tracking = await prisma.vehicleTracking.findMany({
      where: {
        contractId,
        timestamp: {
          gte: since,
        },
      },
      orderBy: {
        timestamp: 'desc',
      },
    });

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

function calculateHaversineDistance(
  lat1: number,
  lon1: number,
  lat2: number,
  lon2: number
): number {
  const R = 6371e3; // Earth's radius in meters
  const φ1 = (lat1 * Math.PI) / 180;
  const φ2 = (lat2 * Math.PI) / 180;
  const Δφ = ((lat2 - lat1) * Math.PI) / 180;
  const Δλ = ((lon2 - lon1) * Math.PI) / 180;

  const a =
    Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
    Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  return R * c; // Distance in meters
}
