<?php

namespace App\Http\Requests;

use App\Models\HomeDashboard;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateHomeWidgetRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $prefix = config("srm_config.installer.table_prefix", "srm_");
        $isTitleRequired = is_array($this->input('resource'));

        $rules =  [
            // 'resource_type' => ['required'],
            'resource' => ['required',function ($attribute, $value, $fail) {
                if(is_array($value) && count($value) > 5) {
                    $fail(trans('home.validations.max.resource', [
                        'num' => 5
                    ]));
                    return;
                }

                $checkHomeDashboardExists = HomeDashboard::where('resource_id', $value)
                ->where('user_id', auth()->user()->user_ID)->exists();
                if($checkHomeDashboardExists) {
                    $fail(trans('home.validations.exists.resource'));
                }
            }],
            'title' => [
                Rule::requiredIf(function () {
                    if(is_array($this->input('resource'))) {
                        return true;
                    }
                }),
                Rule::unique($prefix.'home_dashboard', 'widget_title')
                ->using(function ($q) {
                    $q->where('user_id', auth()->user()->user_ID)
                    ->where('id', '!=', request()->route('widget')->id);
                })

            ]
        ];

        if ($isTitleRequired) {
            $rules['title'][] = 'string';
            $rules['title'][] = 'max:255';
        }

        return $rules;

    }

    public function messages()
    {
        return [
            'resource_type.required' => trans('home.validations.required.resource_type'),
            'resource.required' => trans('home.validations.required.resource'),
            'title.required' => trans('home.validations.required.title'),
            'title.unique' => trans('home.validations.unique.title')
        ];
    }
}
