<?php

namespace App\Http\Requests\Api;

use App\Enums\CustomerDocumentType;
use App\Enums\PermissionSlug;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreCustomerDocumentRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->hasPermission(PermissionSlug::CustomersUpdate) === true
            || $this->user()?->hasPermission(PermissionSlug::CustomersCreate) === true;
    }

    /**
     * @return array<string, ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'type' => ['required', 'string', Rule::in(CustomerDocumentType::values())],
            'file' => ['required', 'file', 'image', 'mimes:jpeg,jpg,png,webp', 'max:5120'],
        ];
    }

    public function documentType(): CustomerDocumentType
    {
        return CustomerDocumentType::from(strtoupper((string) $this->validated('type')));
    }

    protected function prepareForValidation(): void
    {
        if ($this->filled('type')) {
            $this->merge([
                'type' => strtoupper((string) $this->input('type')),
            ]);
        }
    }
}
