import React from 'react';
import { prisma } from '@/lib/prisma';
import HomeClient from './HomeClient';
import { Metadata } from 'next';

export async function generateMetadata(): Promise<Metadata> {
  const settings = await prisma.siteSetting.findUnique({
    where: { id: 'singleton' }
  });

  const title = settings?.siteName || 'Afroprenariat';
  const description = settings?.siteSlogan || "La plateforme de référence pour l'entrepreneuriat africain.";

  return {
    title: {
      default: title,
      template: `%s | ${title}`
    },
    description: description,
    openGraph: {
      title: title,
      description: description,
      url: 'https://afroprenariat.com',
      siteName: title,
      images: [
        {
          url: 'https://images.unsplash.com/photo-1522071820081-009f0129c71c?ixlib=rb-4.0.3&auto=format&fit=crop&w=1200&h=630&q=80',
          width: 1200,
          height: 630,
          alt: title,
        },
      ],
      locale: 'fr_FR',
      type: 'website',
    },
    twitter: {
      card: 'summary_large_image',
      title: title,
      description: description,
      images: ['https://images.unsplash.com/photo-1522071820081-009f0129c71c?ixlib=rb-4.0.3&auto=format&fit=crop&w=1200&h=630&q=80'],
    },
  };
}

export default async function HomePage() {
  // Fetch initial data for faster loading and SEO
  const [featuredBusinesses, posts, categories] = await Promise.all([
    prisma.business.findMany({
      where: { isFeatured: true, isActive: true, isSuspended: false },
      take: 4,
      include: { categoryRef: true }
    }),
    prisma.blogPost.findMany({
      where: { status: 'PUBLISHED', publishedAt: { lte: new Date() } },
      orderBy: { date: 'desc' },
      take: 6
    }),
    prisma.businessCategory.findMany({
      where: { isActive: true },
      take: 8
    })
  ]);

  // Convert to plain objects for client component
  const initialFeatured = JSON.parse(JSON.stringify(featuredBusinesses));
  const initialPosts = JSON.parse(JSON.stringify(posts));
  const initialCategories = JSON.parse(JSON.stringify(categories));

  return (
    <HomeClient 
      initialFeatured={initialFeatured} 
      initialPosts={initialPosts} 
      initialCategories={initialCategories} 
    />
  );
}
