<?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')) {
            Schema::create('order_courier_shipments', function (Blueprint $table) {
                $table->id();
                $table->foreignId('order_id')->unique()->constrained('orders')->cascadeOnDelete();
                $table->string('provider', 50)->index();
                $table->string('courier_service', 100)->nullable();
                $table->string('provider_mode', 20)->default('sandbox');
                $table->string('booking_status', 30)->default('not_sent')->index();
                $table->string('courier_status', 100)->nullable()->index();
                $table->string('courier_parcel_id', 100)->nullable()->index();
                $table->string('courier_tracking_id', 100)->nullable()->index();
                $table->string('courier_consignment_id', 100)->nullable()->index();
                $table->decimal('collectable_amount', 24, 8)->default(0);
                $table->string('parcel_note')->nullable();
                $table->json('request_payload')->nullable();
                $table->json('response_payload')->nullable();
                $table->unsignedSmallInteger('last_http_status')->nullable();
                $table->text('last_error_message')->nullable();
                $table->string('status_mapping_result', 50)->nullable();
                $table->timestamp('sent_to_courier_at')->nullable();
                $table->timestamp('courier_synced_at')->nullable();
                $table->foreignId('sent_by_admin_id')->nullable()->constrained('admins')->nullOnDelete();
                $table->foreignId('last_synced_by_admin_id')->nullable()->constrained('admins')->nullOnDelete();
                $table->timestamps();
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('order_courier_shipments');
    }
};
