<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * Create user_devices table for device management
     * Max 3 devices per user, requires admin approval
     */
    public function up(): void
    {
        Schema::create('user_devices', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('device_id')->comment('Unique device identifier');
            $table->string('device_model')->nullable();
            $table->string('device_brand')->nullable();
            $table->string('os_version')->nullable();
            $table->string('app_version')->nullable();
            $table->string('device_name')->nullable()->comment('User-friendly name like Samsung Galaxy A52');
            $table->enum('status', ['pending', 'approved', 'rejected'])->default('pending');
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('approved_at')->nullable();
            $table->text('rejection_reason')->nullable();
            $table->timestamp('last_used_at')->nullable();
            $table->boolean('is_primary')->default(false)->comment('Primary device for the user');
            $table->timestamps();

            // Unique constraint: one device_id per user
            $table->unique(['user_id', 'device_id']);

            // Index for faster lookups
            $table->index(['user_id', 'status']);
            $table->index('device_id');
        });
    }

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