<?php

namespace App\Http\Requests;

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

class StoreDashboardWidgetRequest 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('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'         => [
                'sometimes',
                Rule::requiredIf(function () {

                    if (is_array($this->input('resource'))) {
                        return true;
                    }

                }),
            ],
        ];

        if ($isTitleRequired) {
            $rules['title'][] = 'string';
            $rules['title'][] = 'max:255';
            $rules['title'][] = Rule::unique($prefix . 'widgets', 'title')
                ->where(function ($q) {
                    $q->where('dashboard_id', request()->route('dashboard')->id)
                        ->whereNotNull('title');
                });

        }

        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'),
        ];
    }

}
