<?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::table('personal_access_tokens', function (Blueprint $table): void {
            $table->char('device_id_hash', 64)->nullable()->after('token_hint');
            $table->string('device_id_preview', 24)->nullable()->after('device_id_hash');
            $table->timestamp('device_bound_at')->nullable()->after('device_id_preview');
            $table->string('first_ip', 45)->nullable()->after('device_bound_at');
            $table->string('last_ip', 45)->nullable()->after('first_ip');
            $table->timestamp('last_seen_at')->nullable()->after('last_ip');
            $table->boolean('device_mismatch_seen')->default(false)->after('last_seen_at');
            $table->index('device_id_hash', 'pat_device_hash_idx');
        });
        Schema::create('earn_api_access_logs', function (Blueprint $table): void {
            $table->bigIncrements('id');
            $table->foreignId('earn_member_id')->nullable()->constrained('earn_members')->nullOnDelete();
            $table->unsignedBigInteger('personal_access_token_id')->nullable();
            $table->string('token_preview', 16)->nullable();
            $table->string('event', 48);
            $table->char('device_id_hash', 64)->nullable();
            $table->string('device_id_preview', 24)->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->string('user_agent', 255)->nullable();
            $table->string('http_method', 10);
            $table->string('route_name', 100)->nullable();
            $table->unsignedSmallInteger('response_status');
            $table->string('failure_code', 48)->nullable();
            $table->timestamp('occurred_at');
            $table->timestamp('created_at')->nullable();
            $table->foreign('personal_access_token_id')->references('id')->on('personal_access_tokens')->nullOnDelete();
            $table->index(['earn_member_id', 'occurred_at'], 'earn_access_member_time_idx');
            $table->index(['personal_access_token_id', 'occurred_at'], 'earn_access_token_time_idx');
            $table->index(['event', 'occurred_at'], 'earn_access_event_time_idx');
            $table->index('occurred_at', 'earn_access_retention_idx');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('earn_api_access_logs');
        Schema::table('personal_access_tokens', function (Blueprint $table): void {
            $table->dropIndex('pat_device_hash_idx');
            $table->dropColumn(['device_id_hash', 'device_id_preview', 'device_bound_at', 'first_ip', 'last_ip', 'last_seen_at', 'device_mismatch_seen']);
        });
    }
};
