<?php

namespace App\Http\Controllers\Frontend;

use App\Enums\ProductStatus;
use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\View\View;

class ProductController extends Controller
{
    private const RECENTLY_VIEWED_COOKIE = 'recently_viewed';

    public function show(Request $request, Product $product): View
    {
        abort_unless($product->status === ProductStatus::Active, 404);

        $product->load(['images', 'variants.color', 'variants.size', 'variants.inventory', 'category', 'brand', 'tags']);
        $product->increment('views_count');

        $relatedProducts = Product::active()
            ->where('id', '!=', $product->id)
            ->where('category_id', $product->category_id)
            ->withRatings()
            ->with('primaryImage')
            ->inRandomOrder()
            ->take(4)
            ->get();

        $reviews = $product->approvedReviews()->with('user')->latest()->get();
        $averageRating = round((float) $reviews->avg('rating'), 1);

        $viewedSlugs = array_filter(explode(',', (string) $request->cookie(self::RECENTLY_VIEWED_COOKIE)));
        $otherViewedSlugs = array_diff($viewedSlugs, [$product->slug]);

        $recentlyViewed = Product::active()
            ->whereIn('slug', array_slice($otherViewedSlugs, 0, 4))
            ->withRatings()
            ->with('primaryImage')
            ->get();

        $updatedCookie = array_slice(array_unique([$product->slug, ...$otherViewedSlugs]), 0, 8);
        Cookie::queue(self::RECENTLY_VIEWED_COOKIE, implode(',', $updatedCookie), 60 * 24 * 30);

        return view('frontend.shop.show', compact('product', 'relatedProducts', 'reviews', 'averageRating', 'recentlyViewed'));
    }
}
