import { getHost } from "../../utils/host";
import { websiteConfig } from "../../utils/rpc";

export async function onRequest (context: any, next: any) {

    console.log('middleware')
    // 拦截一个请求里的数据
    // 可选地修改 `locals` 中的属性
    const host = await getHost(context.request);

    console.log(host)
    // if (host == 'www.zhishihuisheng.com' || host == 'zhishihuisheng.com') {
    //     return next();
    // }

    // 防止无线跳转
    if (context.locals.is_write) {
        return next();
    }

    if (!host) {
        context.locals.is_write = 1;
        return context.rewrite('/404');
    }

    const {code, data} = await websiteConfig(host);

    if (!data || code !== 0) {
        context.locals.is_write = 1;
        return context.rewrite('/404');
    }

    if (!context.locals.is_write) {
        context.locals.is_write = 1;
        context.locals.template_config = data;
        // return context.rewrite('/template/' + data.app_template + context.url.pathname);
    }

    return next();
};