<?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
    {
        // user_quotas: add period column and composite index
        Schema::table('user_quotas', function (Blueprint $table) {
            if (!Schema::hasColumn('user_quotas', 'period')) {
                $table->string('period')->default('month')->after('key');
            }
            $table->index(['user_id','period','key','period_start','period_end'], 'uq_composite');
        });

        // user_addons: soft unique window
        Schema::table('user_addons', function (Blueprint $table) {
            $table->unique(['user_id','addon_id','starts_at','ends_at'], 'user_addons_unique_window');
        });

        // push_logs: indexes and sent_at column
        Schema::table('push_logs', function (Blueprint $table) {
            if (!Schema::hasColumn('push_logs', 'sent_at')) {
                $table->timestamp('sent_at')->nullable()->after('campaign_id');
            }
            $table->index(['user_id','campaign_id'], 'push_logs_user_campaign');
            $table->index(['sent_at']);
        });

        // events: indexes
        Schema::table('events', function (Blueprint $table) {
            $table->index(['type','created_at'], 'events_type_ts');
            $table->index(['user_id','created_at'], 'events_user_ts');
        });
    }

    public function down(): void
    {
        Schema::table('user_quotas', function (Blueprint $table) {
            $table->dropIndex('uq_composite');
            if (Schema::hasColumn('user_quotas', 'period')) {
                $table->dropColumn('period');
            }
        });
        Schema::table('user_addons', function (Blueprint $table) {
            $table->dropUnique('user_addons_unique_window');
        });
        Schema::table('push_logs', function (Blueprint $table) {
            $table->dropIndex('push_logs_user_campaign');
            $table->dropIndex(['sent_at']);
            if (Schema::hasColumn('push_logs', 'sent_at')) {
                $table->dropColumn('sent_at');
            }
        });
        Schema::table('events', function (Blueprint $table) {
            $table->dropIndex('events_type_ts');
            $table->dropIndex('events_user_ts');
        });
    }
};

