<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('order_courier_shipments')) {
            return;
        }

        Schema::table('order_courier_shipments', function (Blueprint $table) {
            if (! Schema::hasColumn('order_courier_shipments', 'courier_id') && Schema::hasTable('couriers')) {
                $table->foreignId('courier_id')->nullable()->after('id')->constrained('couriers')->nullOnDelete();
            }

            if (! Schema::hasColumn('order_courier_shipments', 'customer_delivery_charge')) {
                $table->decimal('customer_delivery_charge', 24, 8)->nullable()->after('collectable_amount');
            }

            if (! Schema::hasColumn('order_courier_shipments', 'delivered_at')) {
                $table->timestamp('delivered_at')->nullable()->after('cod_collected_at');
            }

            if (! Schema::hasColumn('order_courier_shipments', 'net_receivable_amount')) {
                $table->decimal('net_receivable_amount', 24, 8)->nullable()->after('settled_amount');
            }

            if (! Schema::hasColumn('order_courier_shipments', 'net_received_amount')) {
                $table->decimal('net_received_amount', 24, 8)->nullable()->after('net_receivable_amount');
            }

            if (! Schema::hasColumn('order_courier_shipments', 'balance_amount')) {
                $table->decimal('balance_amount', 24, 8)->nullable()->after('net_received_amount');
            }
        });
    }

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

        Schema::table('order_courier_shipments', function (Blueprint $table) {
            foreach ([
                'customer_delivery_charge',
                'delivered_at',
                'net_receivable_amount',
                'net_received_amount',
                'balance_amount',
            ] as $column) {
                if (Schema::hasColumn('order_courier_shipments', $column)) {
                    $table->dropColumn($column);
                }
            }

            if (Schema::hasColumn('order_courier_shipments', 'courier_id')) {
                $table->dropConstrainedForeignId('courier_id');
            }
        });
    }
};
