<?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('licenses', function (Blueprint $table) {
            $table->id();
            $table->string('license_key', 64)->unique();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('product_id')->constrained()->cascadeOnDelete();
            $table->foreignId('order_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('order_item_id')->nullable()->constrained('order_items')->nullOnDelete();

            // License type & state
            $table->enum('type', ['single', 'multi_domain', 'unlimited', 'developer', 'agency', 'lifetime', 'subscription', 'trial', 'beta'])->default('single');
            $table->enum('status', ['active', 'expired', 'suspended', 'revoked', 'cancelled', 'trial', 'pending'])->default('pending');

            // Activation limits
            $table->unsignedInteger('max_activations')->default(1);
            $table->unsignedInteger('activations_count')->default(0);
            $table->unsignedInteger('max_domains')->nullable();

            // Validity
            $table->timestamp('activated_at')->nullable();
            $table->timestamp('expires_at')->nullable(); // null = lifetime
            $table->timestamp('suspended_at')->nullable();
            $table->timestamp('revoked_at')->nullable();
            $table->string('revoke_reason')->nullable();

            // Security
            $table->string('secret_key', 64); // HMAC signing secret
            $table->string('checksum', 64); // integrity check
            $table->boolean('is_trial')->default(false);
            $table->unsignedInteger('trial_days')->nullable();

            // Subscription
            $table->boolean('is_subscription')->default(false);
            $table->string('subscription_id')->nullable();
            $table->timestamp('next_billing_at')->nullable();

            // Notes
            $table->text('notes')->nullable();
            $table->json('meta')->nullable();

            $table->timestamps();
            $table->softDeletes();

            $table->index(['user_id', 'status']);
            $table->index(['product_id', 'status']);
            $table->index('license_key');
            $table->index('status');
            $table->index('expires_at');
        });
    }

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