<?php

declare(strict_types=1);

namespace App\Http\Requests\Warranty;

use App\Enums\WarrantyType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'type' => ['required', Rule::enum(WarrantyType::class)],
            'provider' => ['nullable', 'string', 'max:150'],
            'reference_number' => ['nullable', 'string', 'max:80'],
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date', 'after_or_equal:start_date'],
            'cost' => ['nullable', 'numeric', 'min:0', 'max:99999999999.99'],
            'notes' => ['nullable', 'string', 'max:5000'],
            'make_primary' => ['nullable', 'boolean'],
            'document' => ['nullable', 'file', 'mimes:pdf,jpg,jpeg,png', 'max:10240'],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'end_date.after_or_equal' => __('The end date cannot be before the start date.'),
            'document.mimes' => __('The document must be a PDF, JPG or PNG file.'),
            'document.max' => __('The document cannot be larger than 10 MB.'),
        ];
    }

    protected function prepareForValidation(): void
    {
        $this->merge(WarrantyRules::normalise($this) + [
            'make_primary' => $this->boolean('make_primary'),
        ]);
    }
}
