<?php

namespace App\Http\Controllers\WebAuthn;

use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Response;
use Laragear\WebAuthn\Http\Requests\AssertedRequest;
use Laragear\WebAuthn\Http\Requests\AssertionRequest;

use function response;

class WebAuthnLoginController
{
    /**
     * Returns the challenge to assertion.
     */
    public function options(AssertionRequest $request): Responsable
    {
        \Log::info('WebAuthn Login Options Requested', ['input' => $request->all()]);

        return $request->toVerify($request->validate(['email' => 'sometimes|email|string']));
    }

    /**
     * Log the user in.
     */
    public function login(AssertedRequest $request): Response
    {
        $success = $request->login();

        if ($success) {
            \Log::info('WebAuthn Login Successful', ['user' => auth()->id()]);

            return response()->noContent(204);
        }

        \Log::warning('WebAuthn Login Failed');

        return response()->noContent(422);
    }
}
