<?php

namespace Kylin\LawCase\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Kylin\LawCase\Enums\DocType;
use Kylin\LawCase\Enums\AccessLevel;

/**
 * 文档模型
 *
 * 管理案件相关文档，包括文档编号、类型、访问级别、版本等。
 *
 * @property string $doc_no       文档编号
 * @property string $doc_type     文档类型
 * @property string $access_level 访问级别
 * @property int    $version      版本号
 */
class Document extends Model
{
    use SoftDeletes;

    protected $table = 'kylin_law_documents';

    protected $fillable = [
        'doc_no',
        'doc_type',
        'doc_name',
        'case_id',
        'file_path',
        'file_hash',
        'file_size',
        'is_confidential',
        'access_level',
        'version',
        'parent_id',
        'uploaded_by',
        'description',
    ];

    protected $casts = [
        'doc_type' => DocType::class,
        'access_level' => AccessLevel::class,
        'is_confidential' => 'boolean',
        'file_size' => 'integer',
        'version' => 'integer',
    ];

    public function case()
    {
        return $this->belongsTo(CaseModel::class, 'case_id');
    }

    public function uploader()
    {
        return $this->belongsTo(\App\Models\User::class, 'uploaded_by');
    }

    /**
     * F-DOC-002 版本控制 - 父版本关联
     */
    public function parentDocument()
    {
        return $this->belongsTo(Document::class, 'parent_id');
    }

    public function childVersions()
    {
        return $this->hasMany(Document::class, 'parent_id');
    }

    public function scopeByCase($query, int $caseId)
    {
        return $query->where('case_id', $caseId);
    }

    public function scopeConfidential($query)
    {
        return $query->where('is_confidential', true);
    }

    /**
     * F-DOC-006 文档审批关联
     */
    public function approvals()
    {
        return $this->hasMany(DocumentApproval::class);
    }
}
