<?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\Database\Eloquent\Builder;

final class DberpAuditLogCategoryQuery
{
    public function apply(Builder $query, DberpAuditLogCategory $category): Builder
    {
        return match ($category) {
            DberpAuditLogCategory::FieldChange => $this->applyFieldChange($query),
            DberpAuditLogCategory::Security => $this->applySecurity($query),
            DberpAuditLogCategory::System => $this->applySystem($query),
            DberpAuditLogCategory::Business => $this->applyBusiness($query),
        };
    }

    private function applyFieldChange(Builder $query): Builder
    {
        return $query->where(function (Builder $builder): void {
            foreach (['created', 'updated', 'deleted', 'restored'] as $suffix) {
                $builder->orWhere('action', 'like', '%.'.$suffix);
            }
        });
    }

    private function applySecurity(Builder $query): Builder
    {
        return $query->where(function (Builder $builder): void {
            foreach (['blocked', 'over_limit', 'insufficient_stock', 'credit_check_blocked', 'confirm_blocked'] as $keyword) {
                $builder->orWhere('action', 'like', '%'.$keyword.'%');
            }
        });
    }

    private function applySystem(Builder $query): Builder
    {
        return $query->where(function (Builder $builder): void {
            foreach (['dberp.audit_log.%', 'dberp.report.exported', 'dberp.admin.%', 'dberp.integration.%', 'dberp.auth.%'] as $pattern) {
                $builder->orWhere('action', 'like', $pattern);
            }
        });
    }

    private function applyBusiness(Builder $query): Builder
    {
        return $query
            ->where(function (Builder $builder): void {
                foreach (['created', 'updated', 'deleted', 'restored'] as $suffix) {
                    $builder->where('action', 'not like', '%.'.$suffix);
                }
            })
            ->where(function (Builder $builder): void {
                foreach (['blocked', 'over_limit', 'insufficient_stock', 'credit_check_blocked', 'confirm_blocked'] as $keyword) {
                    $builder->where('action', 'not like', '%'.$keyword.'%');
                }
            })
            ->where(function (Builder $builder): void {
                foreach (['dberp.audit_log.%', 'dberp.report.exported', 'dberp.admin.%', 'dberp.integration.%'] as $pattern) {
                    $builder->where('action', 'not like', $pattern);
                }
            })
            ->where(function (Builder $builder): void {
                $builder->where('action', 'not like', 'dberp.auth.%');
            });
    }
}
