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) {
  try {
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams?.get('page') ?? '1');
    const perPage = parseInt(searchParams?.get('perPage') ?? '20');
    const status = searchParams?.get('status');
    const search = searchParams?.get('search');

    const where: any = {};
    if (status && status !== 'ALL') where.status = status;
    if (search) {
      where.OR = [
        { title: { contains: search, mode: 'insensitive' } },
        { make: { contains: search, mode: 'insensitive' } },
        { model: { contains: search, mode: 'insensitive' } },
      ];
    }

    const [vehicles, total] = await Promise.all([
      prisma.vehicle.findMany({
        where,
        include: { images: { orderBy: { order: 'asc' } }, category: true },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * perPage,
        take: perPage,
      }),
      prisma.vehicle.count({ where }),
    ]);

    return NextResponse.json({ vehicles: vehicles ?? [], total: total ?? 0, page, perPage });
  } catch (error: any) {
    console.error('Vehicles GET error:', error);
    return NextResponse.json({ error: 'Failed to fetch' }, { status: 500 });
  }
}

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

    const data = await request.json();
    const slug = `${(data?.make ?? 'equipo')}-${(data?.model ?? 'unknown')}-${(data?.year ?? 2024)}-${Date.now()}`
      .toLowerCase()
      .replace(/[^a-z0-9-]/g, '-')
      .replace(/-+/g, '-');

    const vehicle = await prisma.vehicle.create({
      data: {
        title: data?.title ?? `${data?.make ?? ''} ${data?.model ?? ''} ${data?.year ?? ''}`.trim(),
        slug,
        description: data?.description ?? null,
        make: data?.make ?? '',
        model: data?.model ?? '',
        year: parseInt(data?.year ?? '2024'),
        price: parseFloat(data?.price ?? '0'),
        mileage: data?.mileage ? parseInt(data.mileage) : null,
        engineType: data?.engineType ?? null,
        transmission: data?.transmission ?? null,
        fuelType: data?.fuelType ?? null,
        horsepower: data?.horsepower ?? null,
        color: data?.color ?? null,
        vin: data?.vin ?? null,
        stockNumber: data?.stockNumber ?? null,
        condition: data?.condition ?? 'Used',
        status: data?.status ?? 'AVAILABLE',
        featured: data?.featured ?? false,
        categoryId: data?.categoryId ?? '',
        images: data?.images ? {
          create: (data.images ?? [])?.map((img: any, i: number) => ({
            cloudStoragePath: img?.cloudStoragePath ?? '',
            isPublic: img?.isPublic ?? true,
            url: img?.url ?? '',
            alt: img?.alt ?? '',
            order: i,
            isPrimary: i === 0,
          })),
        } : undefined,
      },
      include: { images: true, category: true },
    });

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