<?php

namespace App\Http\Requests;

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

class AdminRequest extends FormRequest
{
    use ConvertsBase64ToFiles;

    protected ?Admin $admin = 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()
    {
        return [
            'nombre' => 'required|string|min:2|max:120',
            'apellido' => 'required|string|min:2|max:120',
            'cedula' => [
                'nullable',
                'numeric',
                $this->uniqueRule('personas', $this->admin?->persona)
            ],
            'username' => [
                'required',
                'string',
                'min:2',
                'max:120',
                $this->uniqueRule('admins', $this->admin)
            ],
            'email' => [
                'required',
                'string',
                'max:120',
                'email',
                $this->uniqueRule('admins', $this->admin)
            ],
            'imagen' => $this->imageRule(),
            'estado' => 'nullable',
            'root' => 'required',
            ...$this->passwordRule(),
        ];
    }

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

    protected function prepareForValidation()
    {
        $input = $this->input('data.attributes');

        $this->admin = $this->route()->parameter('admin');

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

    protected function uniqueRule(string $table, $model = null)
    {
        return $this->isMethod('POST') && \is_null($model)
            ? Rule::unique($table)
            : Rule::unique($table)->ignore($model);
    }

    protected function passwordRule()
    {
        return $this->isMethod('POST')
            ? ['password' => 'required|confirmed|string|min:8|max:25']
            : ['password' => 'nullable|confirmed|string|min:8|max:25'];
    }

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