<?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_products')) {
            Schema::table('savings_products', function (Blueprint $table): void {
                if (! Schema::hasColumn('savings_products', 'processing_fee_timing')) {
                    $table->string('processing_fee_timing', 40)->default('manual')->after('processing_fee_value');
                }
            });

            DB::table('savings_products')
                ->where('type', 'thrift_isusu')
                ->update(['processing_fee_timing' => 'withdrawal']);
        }

        if (Schema::hasTable('savings_accounts')) {
            Schema::table('savings_accounts', function (Blueprint $table): void {
                if (! Schema::hasColumn('savings_accounts', 'processing_fee_timing')) {
                    $table->string('processing_fee_timing', 40)->default('manual')->after('processing_fee_amount');
                }
            });

            DB::table('savings_accounts')
                ->where('product_type', 'thrift_isusu')
                ->update(['processing_fee_timing' => 'withdrawal']);
        }

        if (Schema::hasTable('loan_products')) {
            Schema::table('loan_products', function (Blueprint $table): void {
                if (! Schema::hasColumn('loan_products', 'processing_fee_timing')) {
                    $table->string('processing_fee_timing', 40)->default('before_disbursement')->after('processing_fee_value');
                }
            });
        }

        if (Schema::hasTable('loans')) {
            Schema::table('loans', function (Blueprint $table): void {
                if (! Schema::hasColumn('loans', 'processing_fee_timing')) {
                    $table->string('processing_fee_timing', 40)->default('before_disbursement')->after('processing_fee');
                }
            });
        }
    }

    public function down(): void
    {
        foreach ([
            'loans' => 'processing_fee_timing',
            'loan_products' => 'processing_fee_timing',
            'savings_accounts' => 'processing_fee_timing',
            'savings_products' => 'processing_fee_timing',
        ] as $tableName => $column) {
            if (! Schema::hasTable($tableName) || ! Schema::hasColumn($tableName, $column)) {
                continue;
            }

            Schema::table($tableName, function (Blueprint $table) use ($column): void {
                $table->dropColumn($column);
            });
        }
    }
};
