<?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('payments', function (Blueprint $table): void {
            // Add new decimal column next to amount_cents temporarily for safe backfill
            if (! Schema::hasColumn('payments', 'amount')) {
                $table->decimal('amount', 20, 4)->nullable()->after('account_id');
            }
        });

        // Backfill amount from amount_cents if present
        if (Schema::hasColumn('payments', 'amount_cents')) {
            DB::statement('UPDATE payments SET amount = CASE WHEN amount_cents IS NOT NULL THEN amount_cents / 100.0 ELSE amount END');
        }

        // Make amount non-null if desired; keeping nullable to avoid breaking existing rows
        // Drop amount_cents column
        Schema::table('payments', function (Blueprint $table): void {
            if (Schema::hasColumn('payments', 'amount_cents')) {
                $table->dropColumn('amount_cents');
            }
        });
    }

    public function down(): void
    {
        // Recreate amount_cents and backfill from amount, then drop amount
        Schema::table('payments', function (Blueprint $table): void {
            if (! Schema::hasColumn('payments', 'amount_cents')) {
                $table->integer('amount_cents')->nullable()->after('account_id');
            }
        });

        if (Schema::hasColumn('payments', 'amount')) {
            DB::statement('UPDATE payments SET amount_cents = CASE WHEN amount IS NOT NULL THEN ROUND(amount * 100) ELSE amount_cents END');
        }

        Schema::table('payments', function (Blueprint $table): void {
            if (Schema::hasColumn('payments', 'amount')) {
                $table->dropColumn('amount');
            }
        });
    }
};
