<?php

namespace Modules\Identity\Http\Requests;

use App\Models\User;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * @return array<string, array<int, string>>
     */
    public function rules(): array
    {
        return [
            'identifier' => ['required', 'string'],
        ];
    }

    /**
     * "email" or "phone" — the identifier's format determines the channel
     * the code is delivered over.
     */
    public function identifierType(): string
    {
        return filter_var($this->string('identifier'), FILTER_VALIDATE_EMAIL) !== false ? 'email' : 'phone';
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            $identifier = $this->string('identifier')->toString();

            if ($this->identifierType() === 'phone' && ! preg_match('/^\+?[0-9]{7,15}$/', $identifier)) {
                $validator->errors()->add('identifier', 'The identifier must be a valid email address or phone number.');

                return;
            }

            $column = $this->identifierType() === 'email' ? 'email' : 'phone';

            if (User::where($column, $identifier)->exists()) {
                $validator->errors()->add('identifier', 'An account with this '.$column.' already exists.');
            }
        });
    }
}
