<?php

namespace App\Jobs;

use App\Models\PRODUCT\Product;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Foundation\Bus\Dispatchable;
use Laravel\Reverb\Loggers\Log;

class CacheAllProducts implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;

    public function handle(): void
    {
        $cacheKey = 'products:all';

        $products = Product::with('stocknapshot')->get();

        $data = $products->map(function ($product) {
            $stock = $product->stocknapshot?->stock ?? 0;
            $minStock = $product->minStock ?? 0;

            $stockStatus = 'OutOfStock';
            if ($stock > $minStock) {
                $stockStatus = 'inStock';
            } elseif ($stock == $minStock) {
                $stockStatus = 'alertStock';
            }

            $productArray = $product->getAttributes();
            $productArray['stock'] = $stock;
            $productArray['stockStatus'] = $stockStatus;

            return $productArray;
        })->toArray();


        Cache::put($cacheKey, $data, now()->addHours(2));
        Cache::forget('products:cache:building');

    }
}
