<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class AddToCartRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'product_id' => 'required|exists:products,id',
            // Keep qty validation away from min/max numeric validator path
            // to avoid production crashes when assert() is disabled.
            'qty' => ['required', 'regex:/^[0-9]+$/'],
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->input('qty') === null || $this->input('qty') === '') {
            $this->merge(['qty' => '1']);
        }
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $qtyRaw = (string) $this->input('qty', '1');
            $qty = (int) $qtyRaw;

            if ($qty < 1 || $qty > 100) {
                $validator->errors()->add('qty', 'The qty field must be between 1 and 100.');
            }
        });
    }
}
