<?php

namespace App\Http\Controllers\Api\Public;

use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;
use App\Http\Resources\ProductResource;
use App\Models\Banner;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;

class HomeController extends Controller
{
    /**
     * Aggregated home-screen content for the customer app.
     */
    public function index(): JsonResponse
    {
        $categories = Category::active()->roots()
            ->orderBy('sort_order')
            ->limit(12)
            ->get();

        $banners = Banner::active()
            ->orderBy('sort_order')
            ->limit(5)
            ->get()
            ->map(fn($b) => [
                'id'         => $b->id,
                'title'      => $b->title,
                'placement'  => $b->placement,
                'image'      => Storage::disk('public')->url($b->image),
                'link_type'  => $b->link_type,
                'link_value' => $b->link_value,
            ]);

        $featured = Product::where('is_active', true)
            ->where('is_featured', true)
            ->whereHas('vendor', fn($q) => $q->where('status', 'active'))
            ->with(['images', 'vendor'])
            ->orderByDesc('rating_average')
            ->limit(12)
            ->get();

        $flashDeals = Product::where('is_active', true)
            ->whereNotNull('discount_price')
            ->whereHas('vendor', fn($q) => $q->where('status', 'active'))
            ->with(['images', 'vendor'])
            ->orderByDesc('created_at')
            ->limit(8)
            ->get();

        return response()->json([
            'banners'     => $banners,
            'categories'  => CategoryResource::collection($categories),
            'featured'    => ProductResource::collection($featured),
            'flash_deals' => ProductResource::collection($flashDeals),
        ]);
    }
}
