export const dynamic = 'force-dynamic';
import { prisma } from '@/lib/prisma';
import { HomeClient } from './home-client';

export default async function HomePage() {
  let featuredVehicles: any[] = [];
  let categories: any[] = [];
  let stats = { totalVehicles: 0, totalSold: 0 };

  try {
    featuredVehicles = await prisma.vehicle.findMany({
      where: { featured: true, status: 'AVAILABLE' },
      include: { images: { orderBy: { order: 'asc' } }, category: true },
      take: 6,
      orderBy: { createdAt: 'desc' },
    });
    const allCategories = await prisma.category.findMany({
      orderBy: { order: 'asc' },
      include: {
        _count: { select: { vehicles: { where: { status: 'AVAILABLE' } } } },
        children: {
          include: { _count: { select: { vehicles: { where: { status: 'AVAILABLE' } } } } },
        },
      },
    });
    // For parent categories, aggregate child vehicle counts into the parent total
    categories = allCategories.map((cat: any) => {
      if (!cat.parentId && cat.children?.length > 0) {
        const childCount = cat.children.reduce((sum: number, child: any) => sum + (child._count?.vehicles ?? 0), 0);
        return {
          ...cat,
          _count: { vehicles: (cat._count?.vehicles ?? 0) + childCount },
        };
      }
      return cat;
    });
    const totalVehicles = await prisma.vehicle.count({ where: { status: 'AVAILABLE' } });
    const totalSold = await prisma.vehicle.count({ where: { status: 'SOLD' } });
    stats = { totalVehicles, totalSold };
  } catch (e) {
    console.error('Home page data error:', e);
  }

  const baseUrl = process.env.NEXTAUTH_URL || 'https://evotrucksales.abacusai.app';
  const businessJsonLd = {
    '@context': 'https://schema.org',
    '@type': 'AutoDealer',
    name: 'Evo Truck Sales',
    description: 'Quality commercial trucks and heavy equipment for sale. Serving Owner Operators and Fleets in Hillside, NJ.',
    url: baseUrl,
    logo: baseUrl + '/images/logo.png',
    image: baseUrl + '/og-image.png',
    telephone: ['+19085909802', '+19083436096'],
    email: ['junior@evotrucksales.com', 'kein@evotrucksales.com'],
    address: {
      '@type': 'PostalAddress',
      streetAddress: '1444 North Broad St',
      addressLocality: 'Hillside',
      addressRegion: 'NJ',
      postalCode: '07205',
      addressCountry: 'US',
    },
    geo: { '@type': 'GeoCoordinates', latitude: 40.6965, longitude: -74.2291 },
    priceRange: '$$',
    openingHoursSpecification: [
      { '@type': 'OpeningHoursSpecification', dayOfWeek: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], opens: '09:00', closes: '18:00' },
      { '@type': 'OpeningHoursSpecification', dayOfWeek: 'Saturday', opens: '09:00', closes: '15:00' },
    ],
    areaServed: { '@type': 'State', name: 'New Jersey' },
    hasOfferCatalog: {
      '@type': 'OfferCatalog',
      name: 'Commercial Trucks & Heavy Equipment',
      itemListElement: [
        { '@type': 'OfferCatalog', name: 'Commercial Trucks' },
        { '@type': 'OfferCatalog', name: 'Dump Trucks' },
        { '@type': 'OfferCatalog', name: 'Trailers' },
        { '@type': 'OfferCatalog', name: 'Backhoes' },
        { '@type': 'OfferCatalog', name: 'Heavy Equipment' },
      ],
    },
  };

  return (
    <>
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(businessJsonLd) }} />
      <HomeClient featuredVehicles={JSON.parse(JSON.stringify(featuredVehicles ?? []))} categories={JSON.parse(JSON.stringify(categories ?? []))} stats={stats} />
    </>
  );
}