<?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('provider_offers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('offerwall_id')->nullable()->constrained()->nullOnDelete();
            $table->string('provider_offer_id')->nullable();
            $table->string('name');
            $table->text('description')->nullable();
            $table->text('requirements')->nullable();
            $table->json('steps')->nullable();
            $table->json('rewards')->nullable();
            $table->decimal('reward_points', 12, 2)->default(0);
            $table->decimal('payout', 12, 2)->default(0);
            $table->text('icon_url')->nullable();
            $table->string('icon_path')->nullable();
            $table->text('direct_url')->nullable();
            $table->string('launch_mode')->default('iframe');
            $table->string('category')->default('other');
            $table->json('devices')->nullable();
            $table->string('countries')->nullable();
            $table->boolean('is_active')->default(true);
            $table->boolean('is_featured')->default(false);
            $table->boolean('is_hot')->default(false);
            $table->unsignedInteger('sort_order')->default(0);
            $table->timestamp('last_synced_at')->nullable();
            $table->json('raw_payload')->nullable();
            $table->timestamps();

            $table->index(['offerwall_id', 'is_active']);
            $table->index(['category', 'is_active']);
            $table->index(['is_hot', 'is_featured']);
            $table->index(['provider_offer_id', 'offerwall_id']);
        });

        Schema::table('offerwall_clicks', function (Blueprint $table) {
            $table->foreignId('provider_offer_id')->nullable()->after('campaign_id')->constrained('provider_offers')->nullOnDelete();
            $table->index(['provider_offer_id', 'created_at']);
        });
    }

    public function down(): void
    {
        Schema::table('offerwall_clicks', function (Blueprint $table) {
            $table->dropIndex(['provider_offer_id', 'created_at']);
            $table->dropConstrainedForeignId('provider_offer_id');
        });

        Schema::dropIfExists('provider_offers');
    }
};
