export const dynamic = 'force-dynamic';
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(request: Request, { params }: { params: { id: string } }) {
  try {
    const vehicle = await prisma.vehicle.findUnique({
      where: { id: params?.id ?? '' },
      include: { images: { orderBy: { order: 'asc' } }, category: true },
    });
    if (!vehicle) return NextResponse.json({ error: 'Not found' }, { status: 404 });
    return NextResponse.json(vehicle);
  } catch (error: any) {
    console.error('Vehicle GET error:', error);
    return NextResponse.json({ error: 'Failed to fetch' }, { status: 500 });
  }
}

export async function PUT(request: Request, { params }: { params: { id: string } }) {
  try {
    const session = await getServerSession(authOptions);
    if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const data = await request.json();
    
    // Update vehicle
    const updateData: any = {};
    if (data?.title !== undefined) updateData.title = data.title;
    if (data?.description !== undefined) updateData.description = data.description;
    if (data?.make !== undefined) updateData.make = data.make;
    if (data?.model !== undefined) updateData.model = data.model;
    if (data?.year !== undefined) updateData.year = parseInt(data.year);
    if (data?.price !== undefined) updateData.price = parseFloat(data.price);
    if (data?.mileage !== undefined) updateData.mileage = data.mileage ? parseInt(data.mileage) : null;
    if (data?.engineType !== undefined) updateData.engineType = data.engineType;
    if (data?.transmission !== undefined) updateData.transmission = data.transmission;
    if (data?.fuelType !== undefined) updateData.fuelType = data.fuelType;
    if (data?.horsepower !== undefined) updateData.horsepower = data.horsepower;
    if (data?.color !== undefined) updateData.color = data.color;
    if (data?.vin !== undefined) updateData.vin = data.vin;
    if (data?.stockNumber !== undefined) updateData.stockNumber = data.stockNumber;
    if (data?.condition !== undefined) updateData.condition = data.condition;
    if (data?.status !== undefined) updateData.status = data.status;
    if (data?.featured !== undefined) updateData.featured = data.featured;
    if (data?.categoryId !== undefined) updateData.categoryId = data.categoryId;

    const vehicle = await prisma.vehicle.update({
      where: { id: params?.id ?? '' },
      data: updateData,
      include: { images: true, category: true },
    });

    // Handle images if provided
    if (data?.images) {
      // Delete old images
      await prisma.vehicleImage.deleteMany({ where: { vehicleId: params?.id ?? '' } });
      // Create new
      for (let i = 0; i < (data.images?.length ?? 0); i++) {
        const img = data.images[i];
        await prisma.vehicleImage.create({
          data: {
            cloudStoragePath: img?.cloudStoragePath ?? '',
            isPublic: img?.isPublic ?? true,
            url: img?.url ?? '',
            alt: img?.alt ?? '',
            order: i,
            isPrimary: i === 0,
            vehicleId: params?.id ?? '',
          },
        });
      }
    }

    const updated = await prisma.vehicle.findUnique({
      where: { id: params?.id ?? '' },
      include: { images: { orderBy: { order: 'asc' } }, category: true },
    });

    return NextResponse.json(updated);
  } catch (error: any) {
    console.error('Vehicle update error:', error);
    return NextResponse.json({ error: 'Failed to update' }, { status: 500 });
  }
}

export async function DELETE(request: Request, { params }: { params: { id: string } }) {
  try {
    const session = await getServerSession(authOptions);
    if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    await prisma.vehicle.delete({ where: { id: params?.id ?? '' } });
    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('Vehicle delete error:', error);
    return NextResponse.json({ error: 'Failed to delete' }, { status: 500 });
  }
}
