<?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
    {
        Schema::table('agents', function (Blueprint $table): void {
            if (! Schema::hasColumn('agents', 'merchant_type')) {
                $table->string('merchant_type', 30)->default('onboarding')->after('commission_rate');
            }

            if (! Schema::hasColumn('agents', 'onboarding_commission_rate')) {
                $table->decimal('onboarding_commission_rate', 5, 2)->default(10)->after('merchant_type');
            }

            if (! Schema::hasColumn('agents', 'referral_commission_rate')) {
                $table->decimal('referral_commission_rate', 5, 2)->default(5)->after('onboarding_commission_rate');
            }
        });

        DB::table('agents')->orderBy('id')->get()->each(function ($agent): void {
            DB::table('agents')->where('id', $agent->id)->update([
                'onboarding_commission_rate' => $agent->commission_rate ?? 10,
                'referral_commission_rate' => $agent->commission_rate ?? 5,
            ]);
        });

        Schema::table('tenants', function (Blueprint $table): void {
            if (! Schema::hasColumn('tenants', 'agent_commission_type')) {
                $table->string('agent_commission_type', 30)->default('onboarding')->after('agent_assigned_at')->index();
            }
        });

        Schema::table('agent_commissions', function (Blueprint $table): void {
            if (! Schema::hasColumn('agent_commissions', 'commission_type')) {
                $table->string('commission_type', 30)->default('onboarding')->after('commission_rate')->index();
            }
        });
    }

    public function down(): void
    {
        foreach ([
            'agent_commissions' => ['commission_type'],
            'tenants' => ['agent_commission_type'],
            'agents' => ['merchant_type', 'onboarding_commission_rate', 'referral_commission_rate'],
        ] as $table => $columns) {
            Schema::table($table, function (Blueprint $blueprint) use ($table, $columns): void {
                foreach ($columns as $column) {
                    if (Schema::hasColumn($table, $column)) {
                        $blueprint->dropColumn($column);
                    }
                }
            });
        }
    }
};
