<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Mail\EmailChangedSecurityAlertMail;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class SetupEmailController extends Controller
{
    public function create(Request $request): View|RedirectResponse
    {
        $user = $request->user();
        if ($user->hasCompletedOnboarding()) {
            return redirect()->route('dashboard');
        }

        return view('auth.setup-email', [
            'email' => User::isEmailLoginUpgradePlaceholder((string) $user->email)
                ? ''
                : strtolower(trim((string) $user->email)),
        ]);
    }

    public function requestCode(Request $request): RedirectResponse
    {
        $user = $request->user();
        $validated = $request->validate([
            'email' => [
                'required',
                'string',
                'lowercase',
                'email',
                'max:255',
                Rule::unique(User::class, 'email')->ignore((int) $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.');
                    }
                },
            ],
        ]);

        $newEmail = strtolower(trim((string) $validated['email']));
        $oldEmail = strtolower((string) ($user->email ?? ''));
        $nextStep = 'password';

        DB::transaction(function () use ($user, $newEmail, &$nextStep): void {
            $lockedUser = User::query()->whereKey((int) $user->id)->lockForUpdate()->firstOrFail();
            $nextStep = (bool) $lockedUser->needs_password_reset ? 'verified' : 'password';
            $lockedUser->email = $newEmail;
            $lockedUser->email_verified_at = null;
            $lockedUser->onboarding_step = $nextStep;
            $lockedUser->save();
        });

        if ($oldEmail !== '' && $oldEmail !== $newEmail && ! User::isEmailLoginUpgradePlaceholder($oldEmail)) {
            Mail::to($oldEmail)->queue(new EmailChangedSecurityAlertMail($newEmail));
        }

        return redirect()->route($nextStep === 'verified' ? 'setup.password.create' : 'setup.username.create')
            ->with('status', $nextStep === 'verified'
                ? 'Email saved. Continue with password setup.'
                : 'Email saved. Continue with username setup.');
    }
}