<?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
    {
        Schema::create('delivery_assignments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('order_id')->constrained()->cascadeOnDelete();
            $table->foreignId('delivery_partner_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('vendor_id')->constrained()->cascadeOnDelete();

            $table->enum('status', [
                'pending_assignment',   // waiting for a delivery partner
                'offered',             // notified, awaiting accept
                'accepted',
                'arrived_at_vendor',
                'picked_up',
                'on_the_way',
                'arrived_at_customer',
                'delivered',
                'failed_delivery',
                'returned_to_vendor',
                'cancelled',
            ])->default('pending_assignment');

            // Assignment offer window
            $table->timestamp('offer_expires_at')->nullable();
            $table->integer('offer_attempt')->default(1); // how many partners were tried

            // Pickup
            $table->timestamp('arrived_at_vendor_at')->nullable();
            $table->timestamp('picked_up_at')->nullable();
            $table->decimal('cod_amount', 10, 2)->default(0);
            $table->boolean('cod_collected')->default(false);
            $table->timestamp('cod_collected_at')->nullable();

            // Delivery
            $table->timestamp('arrived_at_customer_at')->nullable();
            $table->timestamp('delivered_at')->nullable();
            $table->boolean('delivery_otp_verified')->default(false);
            $table->string('delivery_proof_photo')->nullable();

            // Failed delivery protocol
            $table->integer('delivery_attempt_count')->default(0);
            $table->timestamp('last_attempt_at')->nullable();

            // Earnings
            $table->decimal('delivery_fee', 10, 2)->default(0);
            $table->decimal('partner_earning', 10, 2)->default(0);
            $table->boolean('earning_credited')->default(false);

            $table->timestamps();

            $table->index(['delivery_partner_id', 'status']);
        });
    }

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