<?php

declare(strict_types=1);

namespace app\common\middleware;

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

/**
 * 跨域请求支持（Webman 迁移版）
 * 安全起见，只支持配置中的域名
 */
class AllowCrossDomain implements MiddlewareInterface
{
    protected array $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => '1800',
        'Access-Control-Allow-Methods'     => '*',
        'Access-Control-Allow-Headers'     => '*',
    ];

    public function process(Request $request, callable $handler): Response
    {
        $path = trim($request->path(), '/');
        if (!str_starts_with($path, 'api/') && !str_starts_with($path, 'admin/')) {
            return $handler($request);
        }

        $header = $this->header;

        $origin = $request->header('origin');
        if ($origin) {
            $info = parse_url($origin);
            $corsDomain = explode(',', config('buildadmin.cors_request_domain', ''));
            $corsDomain[] = $request->host(true);

            if (
                in_array('*', $corsDomain)
                || in_array($origin, $corsDomain)
                || (isset($info['host']) && in_array($info['host'], $corsDomain))
            ) {
                $header['Access-Control-Allow-Origin'] = $origin;
            }
        }

        if ($request->method() === 'OPTIONS') {
            return response('', 204, $header);
        }

        $response = $handler($request);
        return $response->withHeaders($header);
    }
}
