<?php

namespace App\Http\Requests;

use App\Models\Admin\Interna;
use App\Traits\ConvertsBase64ToFiles;
use Illuminate\Foundation\Http\FormRequest;

class InternaUpdateRequest extends FormRequest
{
    use ConvertsBase64ToFiles;

    protected ?Interna $interna = null;
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        $isBase64 = isImageBase64($this->input('imageBase64', null));
        return [
            'titulo' => [
                'required',
                'min:3'
            ],
            'descripcion' => 'required|min:10',
            'grupo_interna_id' => 'required',
            'imagen' => $isBase64 ? $this->imageRule() : 'nullable',
        ];
    }


    protected function prepareForValidation()
    {
        $input = $this->input('data.attributes');
        $input = array_merge($input, [
            'imageBase64' => $this->input('data.attributes.imagen', null)
        ]);

        $this->replace($input ?? []);
        if (isImageBase64($input['imageBase64']))
            $this->convertBase64ToFiles();
    }

    protected function base64FileKeys(): array
    {
        return ['imagen'];
    }

    protected function imageRule()
    {
        return [
            'nullable',
            'image',
            'mimes:webp,jpg,png',
            'dimensions:min_width=960,min_height=960'
        ];
    }
}
