<?php

namespace App\Http\Requests;

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

class UpdateDashboardWidgetRequest 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' => ['required',function ($attribute, $value, $fail) {
                if(is_array($value) && count($value) > 5) {
                    $fail(trans('dashboard_widgets.validations.max.resource', [
                        'num' => 5
                    ]));
                    return;
                }

                $checkHomeDashboardExists = DashboardWidget::where('resource_id', $value)
                ->where('dashboard_id', request()->route('dashboard')->id)->exists();
                if($checkHomeDashboardExists) {
                    $fail(trans('dashboard_widgets.validations.exists.resource'));
                }
            }],
            'title' => [
                Rule::requiredIf(function () {
                    if(is_array($this->input('resource'))) {
                        return true;
                    }
                }),
                Rule::unique($prefix.'widgets', 'title')
                ->using(function ($q) {
                    $q->where('dashboard_id', request()->route('dashboard')->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('dashboard_widgets.validations.required.resource_type'),
            'resource.required' => trans('dashboard_widgets.validations.required.resource'),
            'title.required' => trans('dashboard_widgets.validations.required.title'),
            'title.unique' => trans('dashboard_widgets.validations.unique.title')
        ];
    }
}
