<?php

declare(strict_types=1);

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

namespace App\Http\Middleware;

use App\Filament\Pages\HostPluginCenterPage;
use App\Services\Plugin\HostPluginSettingsRouteResolver;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * 阻止已停用或无权限用户直接访问官方插件设置路由。
 */
final class EnsureHostPluginSettingsAccess
{
    public function __construct(
        private readonly HostPluginSettingsRouteResolver $settingsRouteResolver,
    ) {}

    public function handle(Request $request, Closure $next, string $identifier): Response
    {
        $access = $this->settingsRouteResolver->resolveAccess($identifier, $request->user());

        if ($access->isAvailable()) {
            return $next($request);
        }

        $message = trim((string) ($access->userMessage ?? ''));

        if ($message === '') {
            $message = (string) __('dberp.plugin_center.settings.unavailable');
        }

        if ($request->expectsJson()) {
            return response()->json(['message' => $message], 403);
        }

        if (HostPluginCenterPage::canAccess()) {
            return redirect()->to(HostPluginCenterPage::getUrl(panel: 'admin'))
                ->with('host_plugin_settings_notice', $message);
        }

        return redirect()->to(url(trim((string) config('dberp.admin.panel_path', 'admin'), '/')))
            ->with('host_plugin_settings_notice', $message);
    }
}
