<?php

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

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

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

            // name | description | brand | specs | image_url | correction.
            $table->string('field', 24);
            $table->longText('value')->nullable();
            // sha1 of the normalized value — dedupe key (rejects never resurrect).
            $table->char('value_hash', 40);
            // Structured extras (correction target, specs list, etc.).
            $table->json('extra')->nullable();

            $table->string('source', 64);
            $table->unsignedTinyInteger('confidence')->default(50);
            // pending | approved | rejected | applied.
            $table->string('status', 16)->default('pending');

            $table->string('run_id', 40)->nullable();
            $table->timestamp('applied_at')->nullable();
            $table->unsignedInteger('decided_by')->nullable();

            $table->timestamps();

            // One candidate per (product, field, value) — short name (MySQL 64-char limit).
            $table->unique(['product_id', 'field', 'value_hash'], 'pc_data_cand_unique');
            $table->index(['business_id', 'status'], 'pc_data_cand_biz_status');
        });
    }

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