<?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('package_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('package_id')->constrained('packages')->cascadeOnDelete();
            $table->string('status')->default('queued'); // queued, processing, sent, failed, canceled, skipped
            $table->json('target_json'); // e.g., {"phone_id": 1, "number": "+386..."}
            $table->json('payload_json')->nullable(); // per-item overrides and variables
            $table->unsignedTinyInteger('attempts')->default(0);
            $table->text('last_error')->nullable();
            $table->json('result_json')->nullable();
            $table->string('provider_message_id')->nullable();
            $table->decimal('cost', 10, 4)->nullable();
            $table->string('currency', 10)->nullable();
            $table->string('idempotency_key')->nullable();
            $table->timestamps();

            $table->index(['package_id', 'status']);
            $table->unique(['idempotency_key']);
        });
    }

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