<?php

declare(strict_types=1);

namespace app\common\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Request;
use Webman\Http\Response;

/**
 * 加载控制器语言包中间件（Webman 迁移版，等价 ThinkPHP LoadLangPack）
 * 根据当前路由加载对应控制器的语言包到 Translator
 */
class LoadLangPack implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $path = trim($request->path(), '/');
        if (str_starts_with($path, 'api/') || str_starts_with($path, 'admin/')) {
            $this->loadLang($request);
        }
        return $handler($request);
    }

    protected function loadLang(Request $request): void
    {
        $controllerPath = get_controller_path($request);
        if (!$controllerPath) {
            return;
        }

        $langSet = config('lang.default_lang', config('translation.locale', 'zh-cn'));
        $langSet = str_replace('_', '-', strtolower($langSet));

        $path = trim($request->path(), '/');
        $parts = explode('/', $path);
        $app = $parts[0] ?? 'api';

        $langFile = base_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . $app
            . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . $langSet
            . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $controllerPath) . '.php';

        if (is_file($langFile) && class_exists(\support\Translation::class)) {
            $translator = \support\Translation::instance();
            $translator->addResource('phpfile', $langFile, $langSet, $controllerPath);
        }
    }
}
