<?php

declare(strict_types=1);

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.',
    ];

    /**
     * @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;
    }
}
