<?php

declare(strict_types=1);

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

namespace App\Support\AuditLogDisplay;

use App\Business\Audit\Enums\DberpAuditLogCategory;
use Illuminate\Support\Str;

final class DberpAuditLogCategoryResolver
{
    /**
     * @var list<string>
     */
    private const FIELD_CHANGE_SUFFIXES = [
        'created',
        'updated',
        'deleted',
        'restored',
    ];

    /**
     * @var list<string>
     */
    private const SYSTEM_PREFIXES = [
        'dberp.audit_log.',
        'dberp.report.exported',
        'dberp.admin.',
        'dberp.integration.',
        'dberp.auth.',
        'dberp.mcp.',
    ];

    /**
     * @var list<string>
     */
    private const SECURITY_KEYWORDS = [
        'blocked',
        'over_limit',
        'insufficient_stock',
        'credit_check_blocked',
        'confirm_blocked',
    ];

    public function resolve(?string $action): DberpAuditLogCategory
    {
        if ($action === null || $action === '') {
            return DberpAuditLogCategory::System;
        }

        if ($this->isSystemAction($action)) {
            return DberpAuditLogCategory::System;
        }

        if ($this->isSecurityAction($action)) {
            return DberpAuditLogCategory::Security;
        }

        if ($this->isFieldChangeAction($action)) {
            return DberpAuditLogCategory::FieldChange;
        }

        return DberpAuditLogCategory::Business;
    }

    public function label(DberpAuditLogCategory $category): string
    {
        return (string) __('dberp.audit.categories.'.$category->value);
    }

    private function isFieldChangeAction(string $action): bool
    {
        foreach (self::FIELD_CHANGE_SUFFIXES as $suffix) {
            if (Str::endsWith($action, '.'.$suffix)) {
                return true;
            }
        }

        return false;
    }

    private function isSecurityAction(string $action): bool
    {
        foreach (self::SECURITY_KEYWORDS as $keyword) {
            if (Str::contains($action, $keyword)) {
                return true;
            }
        }

        return false;
    }

    private function isSystemAction(string $action): bool
    {
        foreach (self::SYSTEM_PREFIXES as $prefix) {
            if (Str::startsWith($action, $prefix)) {
                return true;
            }
        }

        return false;
    }
}
