import express from 'express';
import tencentcloud from 'tencentcloud-sdk-nodejs';

const app = express();

app.use(express.json());

app.post('/loginTCCC', async (req, res) => {
    const {
        sdkAppId,
        userId,
        secretId,
        secretKey,
        isInternational = false,
    } = req.body ?? {};
    const numericSdkAppId = Number(sdkAppId);

    if (
        !Number.isFinite(numericSdkAppId)
        || numericSdkAppId <= 0
        || !String(userId ?? '').trim()
        || !String(secretId ?? '').trim()
        || !String(secretKey ?? '').trim()
    ) {
        res.status(400).send({
            errMsg: 'sdkAppId、userId、secretId、secretKey 均为必填项',
            type: 'InvalidParams',
        });
        return;
    }

    const CccClient = tencentcloud.ccc.v20200210.Client;
    const clientConfig = {
        credential: {
            secretId: String(secretId).trim(),
            secretKey: String(secretKey).trim(),
        },
        region: isInternational ? 'ap-singapore' : '',
        profile: {
            httpProfile: {
                endpoint: 'ccc.tencentcloudapi.com',
            },
        }
    };
    const client = new CccClient(clientConfig);
    const params = {
        SdkAppId: numericSdkAppId,
        SeatUserId: String(userId).trim(),
    };

    try {
        const data = await client.CreateSDKLoginToken(params);
        res.send({
            token: data.Token,
            sdkUrl: data.SdkURL,
            sdkAppId: numericSdkAppId,
            userId: String(userId).trim(),
        });
    } catch (err) {
        console.log('\x1b[41m 获取Token失败：', err);
        res.status(500).send({
            errMsg: err instanceof Error ? err.message : '获取 Token 失败',
            code: err && typeof err === 'object' && 'code' in err ? err.code : undefined,
        });
    }
});

app.listen(4000, () => {
    console.log('\x1b[42m API Server run success on port 4000');
});