export const dynamic = 'force-dynamic';
import { prisma } from '@/lib/prisma';
import { notFound } from 'next/navigation';
import { VehicleDetailClient } from './vehicle-detail-client';
import { getFileUrl } from '@/lib/s3';
import { Metadata } from 'next';
import { headers } from 'next/headers';

export async function generateMetadata({ params }: { params: { slug: string } }): Promise<Metadata> {
  try {
    const vehicle = await prisma.vehicle.findUnique({
      where: { slug: params.slug },
      include: { images: { orderBy: { order: 'asc' }, take: 1 }, category: true },
    });
    if (!vehicle) return { title: 'Vehicle Not Found' };
    const title = `${vehicle.year} ${vehicle.make} ${vehicle.model} for Sale | Evo Truck Sales`;
    const description = `${vehicle.year} ${vehicle.make} ${vehicle.model}${vehicle.mileage ? ` with ${vehicle.mileage.toLocaleString()} miles` : ''} for sale at Evo Truck Sales in Hillside, NJ. ${vehicle.engineType ? `${vehicle.engineType} engine. ` : ''}Price: $${vehicle.price.toLocaleString()}. Contact us today!`;
    const imageUrl = vehicle.images[0]?.url || '/og-image.png';
    return {
      title,
      description,
      openGraph: { title, description, images: [imageUrl] },
    };
  } catch {
    return { title: 'Vehicle | Evo Truck Sales' };
  }
}

export default async function VehicleDetailPage({ params }: { params: { slug: string } }) {
  const slug = params?.slug;
  if (!slug) return notFound();

  try {
    const vehicle = await prisma.vehicle.findUnique({
      where: { slug },
      include: { images: { orderBy: { order: 'asc' } }, category: true },
    });
    if (!vehicle) return notFound();

    // Increment view count
    await prisma.vehicle.update({ where: { id: vehicle.id }, data: { viewCount: { increment: 1 } } });

    // Resolve image URLs
    const imagesWithUrls = await Promise.all(
      (vehicle?.images ?? [])?.map(async (img: any) => {
        let url = img?.url ?? '';
        if (img?.cloudStoragePath && !url) {
          try {
            url = await getFileUrl(img.cloudStoragePath, img?.isPublic ?? true);
          } catch { url = ''; }
        }
        return { ...img, url };
      })
    );

    const related = await prisma.vehicle.findMany({
      where: { categoryId: vehicle.categoryId, id: { not: vehicle.id }, status: 'AVAILABLE' },
      include: { images: { orderBy: { order: 'asc' } }, category: true },
      take: 3,
    });

    const safeVehicle = JSON.parse(JSON.stringify({ ...(vehicle ?? {}), images: imagesWithUrls }));
    const safeRelated = JSON.parse(JSON.stringify(related ?? []));

    const headersList = headers();
    const host = headersList.get('x-forwarded-host') || process.env.NEXTAUTH_URL?.replace(/^https?:\/\//, '') || 'evotrucksales.abacusai.app';
    const siteUrl = `https://${host}`;
    const primaryImage = imagesWithUrls[0]?.url || '';

    const jsonLd = {
      '@context': 'https://schema.org',
      '@type': 'Vehicle',
      name: vehicle.title,
      description: vehicle.description || `${vehicle.year} ${vehicle.make} ${vehicle.model} for sale`,
      brand: { '@type': 'Brand', name: vehicle.make },
      model: vehicle.model,
      vehicleModelDate: String(vehicle.year),
      mileageFromOdometer: vehicle.mileage ? { '@type': 'QuantitativeValue', value: vehicle.mileage, unitCode: 'SMI' } : undefined,
      fuelType: vehicle.fuelType || undefined,
      vehicleTransmission: vehicle.transmission || undefined,
      vehicleEngine: vehicle.engineType ? { '@type': 'EngineSpecification', name: vehicle.engineType } : undefined,
      color: vehicle.color || undefined,
      vehicleIdentificationNumber: vehicle.vin || undefined,
      itemCondition: vehicle.condition === 'New' ? 'https://schema.org/NewCondition' : 'https://schema.org/UsedCondition',
      offers: {
        '@type': 'Offer',
        price: vehicle.price,
        priceCurrency: 'USD',
        availability: vehicle.status === 'AVAILABLE' ? 'https://schema.org/InStock' : 'https://schema.org/SoldOut',
        seller: {
          '@type': 'AutoDealer',
          name: 'Evo Truck Sales',
          address: { '@type': 'PostalAddress', streetAddress: '1444 North Broad St', addressLocality: 'Hillside', addressRegion: 'NJ', postalCode: '07205', addressCountry: 'US' },
          telephone: '+19085909802',
        },
      },
      image: primaryImage || undefined,
      url: `${siteUrl}/inventory/${vehicle.slug}`,
    };

    return (
      <>
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
        <VehicleDetailClient vehicle={safeVehicle} relatedVehicles={safeRelated} />
      </>
    );
  } catch (e) {
    console.error('Vehicle detail error:', e);
    return notFound();
  }
}
