import { notFound } from "next/navigation";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import RecetteDetail from "./RecetteDetail";
import pool, { initDB } from "@/lib/db";
import { getCustomer } from "@/lib/customerAuth";

export const dynamic = "force-dynamic";

interface Recette {
  id:                       number;
  title:                    string;
  description:              string;
  ingredients:              string[];
  steps:                    string[];
  image_url:                string;
  astuces:                  string[];
  bien_fait:                string[];
  product_id:               number | null;
  product_name:             string | null;
  product_price:            number | null;
  product_image_url:        string | null;
  product_sizes:            string[] | null;
  product_ingredient_index: number | null;
  published:                boolean;
  created_at:               string;
}

async function getRecette(id: string): Promise<Recette | null> {
  try {
    await initDB();
    const { rows } = await pool.query(
      `SELECT r.*,
              p.name      AS product_name,
              p.price     AS product_price,
              p.image_url AS product_image_url,
              p.sizes     AS product_sizes
       FROM recettes r
       LEFT JOIN products p ON p.id = r.product_id
       WHERE r.id = $1 AND r.published = true`,
      [id]
    );
    return rows[0] ?? null;
  } catch {
    return null;
  }
}

export default async function RecetteDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const [recette, customer] = await Promise.all([getRecette(id), getCustomer()]);
  if (!recette) notFound();

  return (
    <>
      <Navbar />
      <RecetteDetail
        isLoggedIn={!!customer}
        title={recette.title}
        description={recette.description}
        image_url={recette.image_url}
        ingredients={recette.ingredients ?? []}
        steps={recette.steps ?? []}
        astuces={recette.astuces ?? []}
        bien_fait={recette.bien_fait ?? []}
        product_id={recette.product_id ?? undefined}
        product_name={recette.product_name ?? undefined}
        product_price={recette.product_price ?? undefined}
        product_image_url={recette.product_image_url ?? undefined}
        product_sizes={recette.product_sizes ?? undefined}
        product_ingredient_index={recette.product_ingredient_index}
      />
      <Footer />
    </>
  );
}
