<?php

declare(strict_types=1);

namespace App\Actions\Fortify;

use App\Models\LoginHistory;
use App\Models\TrustedDevice;
use Illuminate\Http\Request;
use Laravel\Fortify\Actions\RedirectIfTwoFactorAuthenticatable;

/**
 * Extends Fortify's 2FA redirect to skip the challenge when the
 * current device is trusted (active, non-expired TrustedDevice record).
 */
class RedirectIfTwoFactorConfirmable extends RedirectIfTwoFactorAuthenticatable
{
    /**
     * Handle the incoming request.
     *
     * @param  Request  $request
     * @param  callable  $next
     * @return mixed
     */
    public function handle($request, $next)
    {
        $user = $this->validateCredentials($request);

        if ($this->shouldSkipTwoFactor($request, $user)) {
            return $next($request);
        }

        return parent::handle($request, $next);
    }

    /**
     * Determine if 2FA should be skipped because the device is trusted.
     */
    protected function shouldSkipTwoFactor(Request $request, mixed $user): bool
    {
        if (! $user || empty($user->two_factor_secret)) {
            return false;
        }

        $deviceHash = LoginHistory::generateDeviceHash(
            $request->userAgent() ?? '',
            $request->ip() ?? '127.0.0.1',
        );

        $trustedDevice = TrustedDevice::query()
            ->where('user_id', $user->getKey())
            ->where('device_hash', $deviceHash)
            ->active()
            ->first();

        if ($trustedDevice) {
            $trustedDevice->update(['last_used_at' => now()]);

            return true;
        }

        return false;
    }
}
