<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('system_settings')) {
            DB::table('system_settings')->updateOrInsert(
                ['key' => 'default_agent_commission_rate'],
                ['value' => '30'],
            );

            DB::table('system_settings')->updateOrInsert(
                ['key' => 'default_merchant_referral_commission_rate'],
                ['value' => '10'],
            );
        }

        if (! Schema::hasTable('agents')) {
            return;
        }

        DB::table('agents')
            ->where(function ($query): void {
                $query->whereNull('commission_rate')
                    ->orWhere('commission_rate', '<=', 10);
            })
            ->update([
                'commission_rate' => 30,
                'updated_at' => now(),
            ]);

        DB::table('agents')
            ->where(function ($query): void {
                $query->whereNull('onboarding_commission_rate')
                    ->orWhere('onboarding_commission_rate', '<=', 10);
            })
            ->update([
                'onboarding_commission_rate' => 30,
                'updated_at' => now(),
            ]);

        DB::table('agents')
            ->where(function ($query): void {
                $query->whereNull('referral_commission_rate')
                    ->orWhere('referral_commission_rate', '<=', 5);
            })
            ->update([
                'referral_commission_rate' => 10,
                'updated_at' => now(),
            ]);
    }

    public function down(): void
    {
        if (Schema::hasTable('system_settings')) {
            DB::table('system_settings')->updateOrInsert(
                ['key' => 'default_agent_commission_rate'],
                ['value' => '10'],
            );

            DB::table('system_settings')->updateOrInsert(
                ['key' => 'default_merchant_referral_commission_rate'],
                ['value' => '5'],
            );
        }

        if (! Schema::hasTable('agents')) {
            return;
        }

        DB::table('agents')->where('commission_rate', 30)->update([
            'commission_rate' => 10,
            'updated_at' => now(),
        ]);

        DB::table('agents')->where('onboarding_commission_rate', 30)->update([
            'onboarding_commission_rate' => 10,
            'updated_at' => now(),
        ]);

        DB::table('agents')->where('referral_commission_rate', 10)->update([
            'referral_commission_rate' => 5,
            'updated_at' => now(),
        ]);
    }
};
