<?php

namespace Modules\MedDocuments\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * Document type. business_id NULL = system type (shared across tenants,
 * read-only in the UI). A non-null business_id = a tenant's custom type.
 */
class MeddocType extends Model
{
    protected $table = 'meddoc_types';

    protected $guarded = ['id'];

    protected $casts = [
        'retention_days'     => 'integer',
        'requires_signature' => 'boolean',
        'is_active'          => 'boolean',
    ];

    /** The 15 system doc types seeded on install (spec §8). */
    public const SYSTEM_TYPES = [
        'patient_id_proof',
        'insurance_card',
        'consent_form',
        'medical_report',
        'lab_report',
        'imaging_report',
        'prescription',
        'referral_letter',
        'discharge_summary',
        'invoice',
        'receipt',
        'contract',
        'cv',
        'license',
        'certificate',
    ];

    public function isSystem(): bool
    {
        return $this->business_id === null;
    }

    public function documents()
    {
        return $this->hasMany(MeddocDocument::class, 'doc_type_id');
    }

    /**
     * Types visible to a business: its own custom types + all system types.
     */
    public function scopeForBusiness($query, int $businessId)
    {
        return $query->where(function ($q) use ($businessId) {
            $q->whereNull('business_id')->orWhere('business_id', $businessId);
        });
    }
}
