<?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('savings_transactions')) {
            return;
        }

        Schema::table('savings_transactions', function (Blueprint $table): void {
            if (! Schema::hasColumn('savings_transactions', 'processing_fee_amount')) {
                $table->decimal('processing_fee_amount', 14, 2)->default(0)->after('amount');
            }

            if (! Schema::hasColumn('savings_transactions', 'net_amount')) {
                $table->decimal('net_amount', 14, 2)->default(0)->after('processing_fee_amount');
            }
        });

        if (Schema::hasColumn('savings_transactions', 'net_amount')) {
            DB::table('savings_transactions')
                ->where('net_amount', 0)
                ->update(['net_amount' => DB::raw('amount')]);
        }
    }

    public function down(): void
    {
        if (! Schema::hasTable('savings_transactions')) {
            return;
        }

        Schema::table('savings_transactions', function (Blueprint $table): void {
            foreach (['net_amount', 'processing_fee_amount'] as $column) {
                if (Schema::hasColumn('savings_transactions', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};
