<?php

declare(strict_types=1);

namespace App\Http\Requests\Masters;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class StoreAssetCategoryRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'parent_id' => [
                'nullable',
                'integer',
                Rule::exists('asset_categories', 'id')->whereNull('deleted_at'),
            ],
            'name' => ['required', 'string', 'max:100'],
            'code' => [
                'required',
                'string',
                'max:10',
                'regex:/^[A-Z0-9]+$/',
                // Unique across all rows, soft-deleted included: an asset tag
                // built from a reused code would collide with printed labels.
                Rule::unique('asset_categories', 'code'),
            ],
            'depreciation_years' => ['nullable', 'integer', 'min:1', 'max:255'],
            'default_warranty_months' => ['nullable', 'integer', 'min:1', 'max:600'],
            'is_active' => ['required', 'boolean'],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'code.unique' => __('A category with this code already exists. It may be in the deleted list — restore it instead of creating a duplicate.'),
            'code.regex' => __('The code may contain only capital letters and numbers, for example LAP or MON.'),
            'parent_id.exists' => __('The selected parent category no longer exists.'),
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            AssetCategoryRules::validateHierarchy($validator, $this, category: null);
        });
    }

    protected function prepareForValidation(): void
    {
        $this->merge(AssetCategoryRules::normalise($this));
    }
}
