import { RegionModel } from '@db/Region';
import { ServerlistModel } from '@db/Serverlist';
import proxy from 'egg-http-proxy-middleware';

module.exports = () => {
    return async function (ctx, next) {
        if(!ctx.app.config.envToHost) {
            let envToHost = new Map<string, string>();
            let regions = await RegionModel.getAllRegion();
            for(let { env, webHost } of regions) {
                envToHost.set(env, webHost);
            }
            ctx.app.config.envToHost = envToHost;
        }
        if(!ctx.app.config.sidToHost) {
            await getNewHost(ctx);
        }

        let options = {};
        for(let [env, webHost] of ctx.app.config.envToHost) {
            options[`/web/${env}/`] = {
                target: webHost,
                changeOrigin: true,
                secure: true,
                pathRewrite: function(path) {
                    console.log('proxy', path, path.replace(`/web/${env}/`, '/web/'))
                    return path.replace(`/web/${env}/`, '/web/') 
                }
            }
        }
        if(ctx.request.header['is-proxy'] != 'true') {
            let url = getProxyUrl(ctx.request.url);
            if(url) {
                let sid = ctx.request.method == 'GET'? ctx.query.sid.toString(): ctx.request.body.sid.toString();
                if(!ctx.app.config.sidToHost) {
                    await getNewHost(sid);
                }
                if(!!ctx.app.config.sidToHost.get(sid)) {
                    options[url] = {
                        target: ctx.app.config.sidToHost.get(sid),
                        changeOrigin: true,
                        secure: true,
                        headers: { "is-proxy": "true" }
                    }
                }
            }
        }

        return proxy(options)(ctx, next);
    };
  };

  async function getNewHost(ctx) {
    let envToHost = ctx.app.config.envToHost||new Map();
    let sidToHost = new Map<string, string>();
    let servers = await ServerlistModel.getAllServerList();
    for(let { id, env } of servers) {
        let webHost = envToHost.get(env);
        sidToHost.set(id.toString(), webHost);   
    }
    ctx.app.config.sidToHost = sidToHost;
  }

  function getProxyUrl(url: string) {
    const urls = [
        '/cb/treatusername',
        '/cb/treatguildname',
        '/cb/getguildbyuser',
        '/cb/refundioscallback'
    ];
    for(let str of urls) {
        if(url && url.startsWith(str)) {
            return str;
        }
    }
  }