<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\Auth\RegistrationVerificationTokenService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class RegistrationVerificationController extends Controller
{
    public function __construct(
        private readonly RegistrationVerificationTokenService $tokenService
    )
    {
    }

    public function __invoke(string $token): RedirectResponse
    {
        $record = $this->tokenService->findValidRecord($token);

        if (! $record) {
            return redirect(route('login', absolute: false))
                ->withErrors(['email' => 'Verification link is invalid.']);
        }

        $user = User::query()->find((int) $record->user_id);
        if (! $user) {
            DB::table('user_verification_tokens')->where('id', $record->id)->delete();

            return redirect(route('login', absolute: false))
                ->withErrors(['email' => 'Verification link is invalid.']);
        }

        $user->forceFill([
            'email_verified_at' => $user->email_verified_at ?? now(),
            'onboarding_step' => 'verified',
            'is_active' => true,
        ])->save();

        DB::table('user_verification_tokens')
            ->where('id', $record->id)
            ->delete();

        Auth::login($user);

        return redirect('/setup/password')->with('status', 'Email verified. Continue with password setup.');
    }
}
