<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\DB;

class ProductStockIsAvailable implements ValidationRule
{
    /**
     * Check given request of items is available in stock
     */
    public function __construct(
        public int $product_quantity
    ) {}

    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (is_null($value) || ! is_int($value)) {
            return;
        }

        $product = DB::table('products')->where('id', $value)->select(['id', 'stock', 'security_stock'])->first();

        if (is_null($product)) {
            $fail(__('product_id is invalid'));

            return;
        }

        // Get the sellable stock
        $sellable_stock = ($product->security_stock) ? $product->stock - $product->security_stock : $product->stock;

        if ($this->product_quantity > $sellable_stock) {
            $fail(sprintf(':attribute (%s) too much requested, product stock is: %s', $this->product_quantity, $product->stock));
        }
    }
}
