<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('two_factor_codes', function (Blueprint $table) {
            $table->id();

            // Polymorphic relationship to support both User and PortalUser
            $table->morphs('authenticatable'); // Creates authenticatable_id and authenticatable_type

            // The OTP code (hashed for security)
            $table->string('code_hash');

            // When the code expires
            $table->timestamp('expires_at');

            // Track verification attempts for rate limiting
            $table->unsignedTinyInteger('attempts')->default(0);

            // Track if code has been used (prevent reuse)
            $table->boolean('used')->default(false);

            // Track when code was verified
            $table->timestamp('verified_at')->nullable();

            $table->timestamps();

            // Indexes for performance (with custom names to avoid length issues)
            $table->index(['authenticatable_type', 'authenticatable_id', 'expires_at'], '2fa_codes_auth_expires_idx');
            $table->index(['expires_at', 'used'], '2fa_codes_expires_used_idx');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('two_factor_codes');
    }
};
