<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Models\Concerns;

use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;

trait HasOptionalLightApprovalRelations
{
    use OptionalPluginEloquentRelation;

    abstract protected function lightApprovalDocumentType(): string;

    public function approvalInstances(): HasMany
    {
        $instanceClass = 'Loongdom\DberpLightApproval\Models\ApprovalInstance';

        if (! class_exists($instanceClass)) {
            return $this->emptyPluginHasMany();
        }

        return $this->hasMany($instanceClass, 'document_id')
            ->where('document_type', $this->lightApprovalDocumentType())
            ->orderByDesc('id');
    }

    public function approvalLogs(): HasManyThrough
    {
        $logClass = 'Loongdom\DberpLightApproval\Models\ApprovalLog';
        $instanceClass = 'Loongdom\DberpLightApproval\Models\ApprovalInstance';

        if (! class_exists($logClass) || ! class_exists($instanceClass)) {
            return $this->emptyPluginHasManyThrough();
        }

        return $this->hasManyThrough(
            $logClass,
            $instanceClass,
            'document_id',
            'approval_instance_id',
            'id',
            'id',
        )->where('dberp_approval_instances.document_type', $this->lightApprovalDocumentType());
    }
}
