import React from 'react';
import { notFound } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import BusinessDetailClient from './BusinessDetailClient';
import { Metadata } from 'next';

interface Props {
  params: Promise<{ id: string }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  
  const business = await prisma.business.findFirst({
    where: {
      OR: [
        { id: id },
        { slug: id }
      ],
      isActive: true,
      isSuspended: false
    }
  });

  if (!business) return { title: 'Entreprise non trouvée' };

  const title = business.metaTitle || `${business.name} - Afroprenariat`;
  const description = business.metaDescription || (business.description.length > 160 
    ? business.description.substring(0, 157) + '...' 
    : business.description);

  return {
    title,
    description,
    openGraph: {
      title,
      description,
      images: [business.logoUrl],
      type: 'profile',
    },
    twitter: {
      card: 'summary_large_image',
      title,
      description,
      images: [business.logoUrl],
    }
  };
}

export default async function BusinessDetailPage({ params }: Props) {
  const { id } = await params;
  
  const business = await prisma.business.findFirst({
    where: {
      OR: [
        { id: id },
        { slug: id }
      ],
      isActive: true,
      isSuspended: false
    },
    include: {
      offers: true,
      country: true,
      categoryRef: true
    }
  });

  if (!business) {
    notFound();
  }

  // Normalize data for client component (converting Date/Json to plain objects if needed)
  const normalizedBusiness = JSON.parse(JSON.stringify(business));

  return <BusinessDetailClient initialBusiness={normalizedBusiness} />;
}
