import { createHmac } from 'crypto';
import { resolve } from 'path';
import { HttpServer, LogLevel } from 'tsrpc';
import { ServiceType, serviceProto } from './monopoly/protocols/serviceProto';

export async function createHttp() {

    if (G.config.httpPort) {
        G.http = new HttpServer(serviceProto, {
            json: true,
            cors: '*',
            port: G.config.httpPort,
            logLevel: G.argv.logModel as LogLevel,
            apiTimeout:300000,
        });
        setHttp(G.http);
        await G.http.autoImplementApi(resolve(__dirname, 'api_o2s'), true);
        await G.http.start();
    }
}

const secretKey = 'lymaple_heijiao_2023';

export function setHttp(http: HttpServer<ServiceType>) {
    if (!http) return;

    // http.flows.preRecvDataFlow.push(v => {
    //     try {
    //         let json = JSON.parse(v.data as any);
    //         let { sign, ...d } = json;
    //         if (!sign) {
    //             v.conn.sendData('data error');
    //             return undefined;
    //         }
    //         if (!verifySignature(d, sign)) {
    //             v.conn.sendData('sign error');
    //             return undefined;
    //         }
    //         v.data = JSON.stringify(d);
    //         return v;
    //     } catch (error) {
    //         return undefined;
    //     }
    // });
}

/**
 * 生成签名
 */
function generateSignature(data: any, secretKey: string) {
    return createHmac('sha256', secretKey).update(JSON.stringify(data)).digest('hex');
}

/**
 * 验证签名
 */
function verifySignature(data: any, sign: string) {
    return generateSignature(data, secretKey) == sign;
}

