<?php

namespace Modules\Inventory\Http\Requests\Product;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
use Modules\Core\Traits\FailedValidation;
use Modules\Inventory\Models\Product;

class ReorderProductUnitConversionRequest extends FormRequest
{
    use FailedValidation;

    /**
     * Get the validation rules that apply to the request.
     */

    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'ids' => [
                'required',
                'array',
                'min:1',
            ],

            'ids.*' => [
                'required',
                'integer',
                'distinct',
                'exists:product_unit_conversions,id',
            ],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {

            $product = $this->route('product');

            if (!$product instanceof Product) {
                return;
            }

            $ids = collect($this->ids);
            
            $count = $product
                ->unitConversions()
                ->whereIn('id', $ids)
                ->count();

            if ($count !== $ids->count()) {
                $validator->errors()->add(
                    'ids',
                    'Some conversions do not belong to this product.'
                );
            }
        });
    }
}
