<?php

namespace App\Http\Requests\Api\Provider;

use App\Enums\CommercialRegisterType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Enum;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
     */
    public function rules(): array
    {
        $rules = [
            'category_id' => ['required', Rule::exists('categories', 'id')->where('is_active', true)],
            'name' => ['required', 'string', 'min:4', 'max:100'],
            'email' => ['required', 'email', 'unique:service_providers'],
            'phone' => ['required', 'numeric', "starts_with:9665", 'digits:12', 'unique:service_providers'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'nationality_id' => ['required', 'numeric', Rule::exists('nationalities', 'id')->where('is_active', true)],
            'has_commercial_register' => ['required', 'boolean'],
            'cities' => ['required', 'array', 'distinct', 'min:1'],
            'cities.*' => [Rule::exists('cities', 'id')->where('is_active', true)],
        ];
        if (! $this->input('has_commercial_register')) {
            $rules['id_number'] = ['required_if:has_commercial_register,false', 'numeric', 'digits_between:10,20'];
        } else {
            $rules['commercial_register_type'] = ['required_if:has_commercial_register,true', new Enum(CommercialRegisterType::class)];
            $rules['commercial_register_number'] = ['required_if:has_commercial_register,true', 'numeric', 'digits_between:10,20'];
        }
        return $rules;
    }
}
