<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('items')) {
            Schema::table('items', function (Blueprint $table) {
                if (! Schema::hasColumn('items', 'meta_ad_priority')) {
                    $table->string('meta_ad_priority', 10)->default('medium')->index();
                }
                if (! Schema::hasColumn('items', 'meta_ads_high_profit')) {
                    $table->boolean('meta_ads_high_profit')->default(false)->index();
                }
                if (! Schema::hasColumn('items', 'meta_ads_excluded')) {
                    $table->boolean('meta_ads_excluded')->default(false)->index();
                }
                if (! Schema::hasColumn('items', 'meta_ads_exclusion_mode')) {
                    $table->string('meta_ads_exclusion_mode', 20)->nullable();
                }
                if (! Schema::hasColumn('items', 'meta_ads_exclusion_reason')) {
                    $table->string('meta_ads_exclusion_reason')->nullable();
                }
                if (! Schema::hasColumn('items', 'meta_ads_excluded_at')) {
                    $table->timestamp('meta_ads_excluded_at')->nullable();
                }
            });
        }

        if (! Schema::hasTable('meta_ads_product_rule_settings')) {
            Schema::create('meta_ads_product_rule_settings', function (Blueprint $table) {
                $table->id();
                $table->boolean('auto_exclude_enabled')->default(false);
                $table->boolean('auto_restore_enabled')->default(true);
                $table->unsignedInteger('minimum_final_orders')->default(3);
                $table->decimal('maximum_return_rate', 8, 2)->default(20);
                $table->decimal('minimum_profit', 24, 8)->default(0);
                $table->decimal('high_profit_minimum_profit', 24, 8)->default(1000);
                $table->decimal('high_profit_minimum_roas', 12, 4)->default(1.5);
                $table->foreignId('updated_by_admin_id')->nullable()->constrained('admins')->nullOnDelete();
                $table->timestamps();
            });

            DB::table('meta_ads_product_rule_settings')->insert([
                'auto_exclude_enabled' => false,
                'auto_restore_enabled' => true,
                'minimum_final_orders' => 3,
                'maximum_return_rate' => 20,
                'minimum_profit' => 0,
                'high_profit_minimum_profit' => 1000,
                'high_profit_minimum_roas' => 1.5,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        if (! Schema::hasTable('meta_ads_product_rule_logs')) {
            Schema::create('meta_ads_product_rule_logs', function (Blueprint $table) {
                $table->id();
                $table->unsignedBigInteger('item_id')->index();
                $table->string('action', 50);
                $table->string('source', 20)->default('auto');
                $table->json('before_state')->nullable();
                $table->json('after_state')->nullable();
                $table->json('metrics')->nullable();
                $table->foreignId('admin_id')->nullable()->constrained('admins')->nullOnDelete();
                $table->timestamps();
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('meta_ads_product_rule_logs');
        Schema::dropIfExists('meta_ads_product_rule_settings');

        if (Schema::hasTable('items')) {
            foreach ([
                'meta_ad_priority',
                'meta_ads_high_profit',
                'meta_ads_excluded',
            ] as $indexedColumn) {
                if (Schema::hasColumn('items', $indexedColumn)
                    && Schema::hasIndex('items', [$indexedColumn])
                ) {
                    Schema::table('items', function (Blueprint $table) use ($indexedColumn) {
                        $table->dropIndex([$indexedColumn]);
                    });
                }
            }

            $columns = collect([
                'meta_ad_priority',
                'meta_ads_high_profit',
                'meta_ads_excluded',
                'meta_ads_exclusion_mode',
                'meta_ads_exclusion_reason',
                'meta_ads_excluded_at',
            ])->filter(fn (string $column) => Schema::hasColumn('items', $column))->all();

            if ($columns !== []) {
                Schema::table('items', function (Blueprint $table) use ($columns) {
                    $table->dropColumn($columns);
                });
            }
        }
    }
};
