<?php

use App\Models\Shipment;
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('shipments', function (Blueprint $table) {
            $table->string('consignment_no')->nullable()->after('tracking_number');
            $table->string('service_type')->nullable()->after('package_description');
            $table->string('delivery_mode')->nullable()->after('service_type');
            $table->unsignedTinyInteger('progress_percent')->default(0)->after('status');
            $table->text('comment')->nullable()->after('notes');
            $table->dateTime('arrival_at')->nullable()->after('expected_delivery');
        });

        Shipment::query()->each(function (Shipment $shipment) {
            $progress = match ($shipment->status) {
                'pending' => 8,
                'processing' => 15,
                'picked_up' => 25,
                'in_transit' => 50,
                'at_customs' => 70,
                'out_for_delivery' => 88,
                'delivered' => 100,
                'on_hold' => 40,
                default => 12,
            };

            $shipment->update([
                'consignment_no' => $shipment->consignment_no ?: 'Accessway Express Courier',
                'service_type' => $shipment->service_type ?: 'Parcel',
                'delivery_mode' => $shipment->delivery_mode ?: 'COURIER',
                'progress_percent' => $shipment->progress_percent ?: $progress,
                'arrival_at' => $shipment->arrival_at ?: optional($shipment->expected_delivery)?->setTime(10, 10),
                'comment' => $shipment->comment ?: 'Notice: Note: The receiver is expected to pay the clearance fee as soon as the parcel arrives at destination.',
            ]);
        });
    }

    public function down(): void
    {
        Schema::table('shipments', function (Blueprint $table) {
            $table->dropColumn([
                'consignment_no',
                'service_type',
                'delivery_mode',
                'progress_percent',
                'comment',
                'arrival_at',
            ]);
        });
    }
};
