<?php

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

class CreatePcSearchQueueTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('pc_search_queue')) {
            return;
        }

        Schema::create('pc_search_queue', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('business_id')->index();
            $table->unsignedInteger('product_id');

            // Why this row was enqueued: new | edited | manual | backfill.
            $table->string('reason', 16)->default('manual');
            // Lifecycle: queued | processing | done | failed | skipped.
            $table->string('status', 16)->default('queued')->index();
            // Higher runs first (edited=5, manual/backfill=0).
            $table->smallInteger('priority')->default(0);

            $table->unsignedTinyInteger('attempts')->default(0);
            $table->text('last_error')->nullable();
            $table->unsignedInteger('queued_by')->nullable();

            $table->timestamp('processing_started_at')->nullable();
            $table->timestamp('processed_at')->nullable();
            // Compact per-run counts (parts/devices/barcodes/candidates/ai).
            $table->json('result_summary')->nullable();

            $table->timestamps();

            // One live row per product — re-enqueue resets the same row.
            $table->unique(['business_id', 'product_id'], 'pc_search_queue_unique');
        });
    }

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