<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace app\middleware;

use addons\webman\model\Channel;
use support\Cache;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

/**
 * 站点验证中间件
 * Class SiteAuthMiddleware
 * @package app\middleware
 */
class SiteAuthMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        // 站点标识
        $siteId = $request->header('Site-Id');
        // 排除接口
        if ($request->path() == '/api/v1/talk-pay-notify') {
            return $handler($request);
        }
        if (empty($siteId)) {
            return response('fail', 400);
        }
        $cacheKey = "channel_" . $siteId;
        $channel = Cache::get($cacheKey);
        if (empty($channel)) {
            /** @var Channel $channel */
            $channel = Channel::where('site_id', $siteId)->whereNull('deleted_at')->first();
            if (!empty($channel)) {
                $cacheKey = "channel_" . $channel->site_id;
                Cache::set($cacheKey, $channel->toArray());
            } else {
                return response('fail', 400);
            }
        }
        if ($channel['status'] == 0 || !empty($channel['deleted_at'])) {
            return response('fail', 400);
        }
        $request->department_id = $channel['department_id'];
        $request->site_id = $siteId;

        return $handler($request);
    }
}
