<?php

namespace Modules\Admin\app\Http\Requests;

use App\Models\Client;
use Illuminate\Foundation\Http\FormRequest;
use Modules\Admin\app\Rules\PasswordRule;
use Modules\Admin\app\Rules\PointRule;

class ClientRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $actionMethod = $this->route()->getActionMethod();
        $rules = [
            'id' => [
                'exists' => 'exists:' . (new Client)->getTable() . ',id'
            ],
            'password' => ['nullable', new PasswordRule],
            'name' => 'min:5|max:100',
            'email' => 'email|nullable|unique:' . (new Client)->getTable(),
            'phone' => 'max:50|nullable',
            'company' => 'max:100|nullable',
            'point' => [
                new PointRule,
                'nullable'
            ],
            'avatar' => 'file|mimes:jpeg,jpg,png|nullable',
            'country_code' => 'exists:h_country,code|max:2',
        ];

        if ($actionMethod === 'create') {
            $rules = array_merge($rules, [
                'name' => 'required|' . $rules['name']
            ]);
        }

        if ($actionMethod === 'update') {
            unset($rules['email'], $rules['avatar']);
        }

        if ($actionMethod === 'deletes') {
            $rules = array_merge($rules, [
                'clients.*.id' => 'required|' . $rules['id']['exists'],
            ]);
        }

        if ($actionMethod === 'updates') {
            $rules = array_merge($rules, [
                'clients.*.id' => 'required|' . $rules['id']['exists'],
                'clients.*.password' => $rules['password'],
                'clients.*.name' => $rules['name'],
                'clients.*.email' => $rules['email'],
                'clients.*.phone' => $rules['phone'],
                'clients.*.company' => $rules['company'],
                'clients.*.point' => $rules['point'],
                'clients.*.avatar' => $rules['avatar'],
                'clients.*.country_code' => $rules['country_code'],
            ]);
        }

        if ($actionMethod === 'creates') {
            $rules = array_merge($rules, [
                'clients.*.name' => 'required|' . $rules['name'],
                'clients.*.email' => 'required|' . $rules['email'],
                'clients.*.password' => $rules['password'],
                'clients.*.phone' => $rules['phone'],
                'clients.*.company' => $rules['company'],
                'clients.*.point' => $rules['point'],
                'clients.*.avatar' => $rules['avatar'],
                'clients.*.country_code' => $rules['country_code'],
            ]);
        }

        return $rules;
    }

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }
}
