<?php

namespace Modules\Bms\Entities;

use Illuminate\Database\Eloquent\Model;

class BmsMatchingSetting extends Model
{
    protected $table = 'bms_matching_settings';

    protected $fillable = [
        'business_id', 'threshold', 'weights', 'updated_by',
    ];

    protected $casts = [
        'threshold' => 'integer',
        'weights'   => 'array',
    ];

    /**
     * Resolve the matching settings for a business, falling back to the
     * config defaults when no row has been saved yet.
     */
    public static function resolve(int $businessId): self
    {
        $row = static::firstOrNew(['business_id' => $businessId]);

        if (! $row->exists) {
            $row->threshold = (int) config('bms.matching.threshold', 60);
            $row->weights   = (array) config('bms.matching.weights', []);
        }

        if (empty($row->weights)) {
            $row->weights = (array) config('bms.matching.weights', []);
        }

        return $row;
    }
}
