<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('webauthn_credentials', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('name');
            // Credential IDs can be up to 1023 bytes (base64url ~1364 chars) — too long for
            // a unique index, so store the full value in TEXT and enforce uniqueness on a
            // fixed-length sha256 hash of it.
            $table->text('credential_id');
            $table->char('credential_id_hash', 64);
            $table->text('public_key');               // serialized PublicKeyCredentialSource (JSON)
            $table->string('aaguid')->nullable();
            $table->json('transports')->nullable();
            $table->unsignedBigInteger('sign_count')->default(0);
            $table->timestamp('last_used_at')->nullable();
            $table->timestamps();

            $table->unique(['user_id', 'credential_id_hash'], 'webauthn_user_credential_unique');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('webauthn_credentials');
    }
};
