<?php

declare(strict_types=1);

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.%');
            });
    }
}
