<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use App\Models\Product;
use App\Models\Ingredient;

class ProductController extends Controller
{
    public function index(): JsonResponse
    {
        $products = Product::all();
        $ingredients = Ingredient::all()->keyBy('id');
        
        $productsWithIngredients = $products->map(function ($product) use ($ingredients) {
            $productData = $product->toArray();
            
            if (isset($productData['products']) && is_array($productData['products'])) {
                $productData['products'] = collect($productData['products'])->map(function ($item) use ($ingredients) {
                    if (isset($item['data']['ingredients'])) {
                        $item['data']['ingredients'] = collect($item['data']['ingredients'])
                            ->map(fn($id) => $ingredients->get($id))
                            ->filter()
                            ->values()
                            ->toArray();
                    }
                    return $item;
                })->toArray();
            }
            
            return $productData;
        });

        return response()->json([
            'status' => 'success',
            'data' => $productsWithIngredients
        ]);
    }
}
