// ------ 用户登录 --------
cache.new('sms-verify')

'use api/lib/protect.js'

function main() {
    switch (payload.get().method) {
        case 'GET':
            return create()
        case 'PUT':
            return callback()
        case 'POST':
            return check()
        default:
            response.status.notFound()
            return `404 page not found`
    }
}

function create() {
    const phone = payload.get().path.split('/').pop()

    // 随机6位验证码
    let code = ex.random(6, 'number');

    cache.set('sms-verify', id, { code: code, status: 0 }, 100 * 1000)

    return okMsg({ code: code });
}

function check() {
    let phone = payload.get().path.split('/').pop()
    let code = payload.get().query.code[0]
    let info = cache.get('sms-verify', phone)
    if (!info || info.code != code) {
        return errMsg(511, '会话过期');
    }

    switch (info.status) {
        case 0:
            return okMsg(null);
        case 1:
            cache.del('sms-verify', phone)
            return okMsg(true);
        default:
            return errMsg(511, '验证码错误');
    }
}

function callback() {
    let result = payload.get().body?.toObject()
    // {
    //   "id": "2a70c6bb4f2845da816ea1bfe5732747",
    //   "mobile": "15205201314",
    //   "reply_time": "2014-03-17 22:55:21",
    //   "text": "收到了，谢谢！",
    //   "extend": "01",
    //   "base_extend": "8888",
    //   "_sign": "393d079e0a00912335adfe46f4a2e10f"
    // }
    if (cache.get('sms-verify', result.mobile) == result.text) {
        cache.set('sms-verify', result.mobile, { code: code, status: 1 }, 100 * 1000)
    }
    return okMsg(true);
}
