<?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('user_subscriptions', function (Blueprint $table) {
            $table->ulid('id')->primary();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('plan'); // free, starter, growth, pro
            $table->string('period')->nullable(); // monthly, yearly, lifetime
            $table->string('source'); // iap_android, iap_ios, stripe, paypal, voucher, admin
            $table->string('product_id')->nullable(); // IAP product ID
            $table->string('transaction_id')->nullable(); // IAP / Stripe / PayPal
            $table->text('receipt_data')->nullable(); // raw receipt JSON
            $table->decimal('amount_paid', 10, 2)->nullable();
            $table->string('currency')->nullable();
            $table->string('voucher_code')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamp('starts_at')->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->timestamps();

            $table->index('user_id');
            $table->index(['user_id', 'is_active']);
            $table->index('transaction_id');
        });

        Schema::create('devices', function (Blueprint $table) {
            $table->ulid('id')->primary();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('device_id')->unique();
            $table->string('platform'); // android, ios
            $table->string('model')->nullable();
            $table->string('os_version')->nullable();
            $table->string('app_version')->nullable();
            $table->string('fcm_token')->nullable();
            $table->string('local_ip')->nullable();
            $table->bigInteger('storage_used_bytes')->default(0);
            $table->timestamp('last_sync_at')->nullable();
            $table->boolean('is_revoked')->default(false);
            $table->timestamps();

            $table->index('user_id');
            $table->index('device_id');
            $table->index('fcm_token');
        });
    }

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