<?php

namespace Modules\ProductCompat\Entities;

use App\Product;
use Illuminate\Database\Eloquent\Model;

/**
 * A review-first data candidate produced by the aggressive/AI enrichment run:
 * a proposed name / description / brand / spec set / image URL / correction for
 * a product. Nothing is applied until a human approves it. The (product, field,
 * value_hash) unique index means a rejected value can never resurrect on a
 * later run.
 */
class PcDataCandidate extends Model
{
    protected $table = 'pc_data_candidates';

    protected $fillable = [
        'business_id', 'product_id', 'field', 'value', 'value_hash', 'extra',
        'source', 'confidence', 'status', 'run_id', 'applied_at', 'decided_by',
    ];

    protected $casts = [
        'extra'      => 'array',
        'applied_at' => 'datetime',
    ];

    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id');
    }

    /**
     * Stable dedupe hash for a candidate value: sha1 of the field plus a
     * whitespace-collapsed, lower-cased, trimmed value. Same value under the
     * same field always hashes identically regardless of casing/spacing.
     */
    public static function makeHash(string $field, string $value): string
    {
        return sha1($field . '|' . mb_strtolower(trim(preg_replace('/\s+/', ' ', $value))));
    }
}
