<?php

namespace App\Http\Controllers\WebAuthn;

use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Response;
use Laragear\WebAuthn\Http\Requests\AttestationRequest;
use Laragear\WebAuthn\Http\Requests\AttestedRequest;

use function response;

class WebAuthnRegisterController
{
    /**
     * Returns a challenge to be verified by the user device.
     */
    public function options(AttestationRequest $request): Responsable
    {
        \Log::info('WebAuthn Registration Options Requested', ['user' => auth()->id()]);

        return $request
            // ->fastRegistration() // Removed to allow more compatibility on local dev
            ->allowDuplicates()    // Allow re-registering for testing
            ->toCreate();
    }

    /**
     * Registers a device for further WebAuthn authentication.
     */
    public function register(AttestedRequest $request): Response
    {
        try {
            $request->save();
            \Log::info('WebAuthn Registration Successful', ['user' => auth()->id()]);

            return response()->noContent();
        } catch (\Exception $e) {
            \Log::error('WebAuthn Registration Failed', [
                'user' => auth()->id(),
                'error' => $e->getMessage(),
            ]);

            return response()->json(['error' => $e->getMessage()], 422);
        }
    }
}
