<?php

namespace App\Http\Requests\Admin;

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

class InternaBorradorRequest 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'
            ],
            'grupo_interna_id' => 'required',
            'imagen' => $isBase64 ? $this->imageRule() : 'nullable',
        ];
    }


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

        $this->replace($input ?? []);

        $this->convertBase64ToFiles();
    }

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

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