<?php

declare(strict_types=1);

namespace App\Http\Requests\Settings;

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

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

    protected function prepareForValidation(): void
    {
        if ($this->has('new_email')) {
            $this->merge([
                'new_email' => strtolower(trim((string) $this->input('new_email'))),
            ]);
        }
    }

    public function rules(): array
    {
        return [
            'new_email' => [
                'required',
                'string',
                'lowercase',
                'email',
                'max:255',
                Rule::unique(User::class, 'email')->ignore((int) $this->user()->id),
                function (string $attribute, mixed $value, \Closure $fail): void {
                    if (User::isEmailLoginUpgradePlaceholder((string) $value)) {
                        $fail('Please enter a real email address you can access.');

                        return;
                    }

                    if (strtolower((string) $value) === strtolower((string) $this->user()->email)) {
                        $fail('Please enter a different email address.');
                    }
                },
            ],
        ];
    }
}
