<?php

namespace Modules\VetClinic\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * Item #4a — single finding row inside a body-system's checklist.
 * business_id=null is a system default; a business row with the same
 * (system_key, value) shadows it at lookup time.
 */
class VcSystemFinding extends Model
{
    protected $table = 'vc_system_findings';
    protected $guarded = ['id'];
    protected $casts = [
        'supports_severity' => 'boolean',
        'supports_lr'       => 'boolean',
        'is_critical'       => 'boolean',
        'sort_order'        => 'integer',
    ];

    public function scopeActive($q)             { return $q->where('status', 'active'); }
    public function scopeForBusiness($q, $bid)
    {
        return $q->where(function ($qq) use ($bid) {
            $qq->whereNull('business_id')->orWhere('business_id', $bid);
        });
    }

    /**
     * Resolve the catalogue for a system_key: business overrides shadow
     * same-keyed system defaults (matched on the `value` column).
     */
    public static function catalogueFor(int $businessId, string $systemKey): array
    {
        $rows = static::active()->forBusiness($businessId)
            ->where('system_key', $systemKey)
            ->orderBy('sort_order')->orderBy('label')->get();
        // Override pass: business rows displace system rows that share value.
        $byValue = [];
        foreach ($rows as $r) {
            $key = $r->value;
            // Business override wins over a previously-set system default.
            if (!isset($byValue[$key]) || $r->business_id !== null) {
                $byValue[$key] = $r;
            }
        }
        return array_values(array_map(function ($r) {
            return [
                'value'    => $r->value,
                'label'    => $r->label,
                'severity' => (bool) $r->supports_severity,
                'lr'       => (bool) $r->supports_lr,
                'critical' => (bool) $r->is_critical,
            ];
        }, $byValue));
    }
}
