<?php

namespace Kylin\Wechat\Http\Middleware;

use Closure;
use Illuminate\Contracts\Container\Container;
use Illuminate\Http\Request;
use Illuminate\Session\Store as SessionStore;
use Kylin\Wechat\Events\WeChatUserAuthorized;

/**
 * 微信OAuth授权中间件
 */
class OAuthAuthenticate
{
    /**
     * 创建一个新的中间件实例
     */
    public function __construct(
        private readonly Container $container,
        private readonly SessionStore $session
    ) {}

    /**
     * 处理传入的请求
     */
    public function handle(Request $request, Closure $next, string $account = 'default', string $scope = 'snsapi_userinfo'): mixed
    {
        $config = $this->container['config']->get("wechat.accounts.official_account.{$account}", []);

        if (empty($config)) {
            throw new \InvalidArgumentException("微信公众号配置 '{$account}' 未找到。");
        }

        $officialAccount = $this->container['wechat']->officialAccount($account);

        // 检查会话中是否已有用户信息
        $sessionKey = "easywechat.oauth_user.{$account}";
        $user = $this->session->get($sessionKey);

        if (!$user) {
            // 检查请求中是否有code
            if (!$request->has('code')) {
                // 重定向到微信授权页面
                $redirectUrl = $officialAccount->oauth->scopes([$scope])->redirect($request->fullUrl());
                return redirect($redirectUrl);
            }

            // 从微信获取用户信息
            $user = $officialAccount->oauth->userFromCode($request->get('code'));

            // 将用户信息存储到会话
            $this->session->put($sessionKey, $user);

            // 触发事件
            event(new WeChatUserAuthorized($user, $account));
        }

        // 将用户信息存储到请求
        $request->merge(['wechat_user' => $user]);

        return $next($request);
    }
}