<?php

use App\Models\SupplierPayment;
use App\Support\SupplierPaymentExchange;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('supplier_payments', function (Blueprint $table) {
            $table->decimal('bill_amount', 15, 2)->nullable()->after('amount');
        });

        SupplierPayment::query()->each(function (SupplierPayment $payment): void {
            $billCurrency = (string) ($payment->bill_currency ?? $payment->currency);

            $billAmount = SupplierPaymentExchange::toBillCurrency(
                (float) $payment->amount,
                $payment->currency,
                $billCurrency,
                $payment->exchange_rate !== null ? (float) $payment->exchange_rate : null,
            );

            $payment->update(['bill_amount' => $billAmount]);
        });
    }

    public function down(): void
    {
        Schema::table('supplier_payments', function (Blueprint $table) {
            $table->dropColumn('bill_amount');
        });
    }
};
