<?php

namespace Modules\MedRegistry\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A module activation for a business, optionally narrowed to a facility
 * (business_location_id) or department (department_id). NULL scope columns =
 * tenant-level. settings holds the P1-T5 per-instance JSON settings.
 */
class MedregModuleInstance extends Model
{
    protected $table = 'medreg_module_instances';

    protected $guarded = ['id'];

    protected $casts = [
        'settings'     => 'array',
        'installed_at' => 'datetime',
    ];

    const STATUS_INSTALLED   = 'installed';
    const STATUS_ENABLED     = 'enabled';
    const STATUS_DISABLED    = 'disabled';
    const STATUS_SOFT_LOCKED = 'soft_locked';

    const STATUSES = [
        self::STATUS_INSTALLED,
        self::STATUS_ENABLED,
        self::STATUS_DISABLED,
        self::STATUS_SOFT_LOCKED,
    ];

    public function module()
    {
        return $this->belongsTo(MedregModule::class, 'module_id');
    }

    public function isTenantLevel(): bool
    {
        return is_null($this->business_location_id) && is_null($this->department_id);
    }

    /** Human-readable scope for UI/reports. */
    public function scopeLabel(): string
    {
        if (! is_null($this->department_id)) {
            return 'department #' . $this->department_id;
        }
        if (! is_null($this->business_location_id)) {
            return 'location #' . $this->business_location_id;
        }

        return 'tenant';
    }
}
