/**
 * 用 JKES token 拉取 getMyInfo 并更新 lepao_account（沐晨乐跑 / JKES 唯一数据源）
 */
const db = require('../DataBase/db.js')
const { jkesRequest } = require('./request.js')
const { resolveQQAvatarFromEmail } = require('./resolveQQAvatar.js')

const DEFAULT_AVATAR =
    'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'
const LOGIN_EXPIRED_MSG = '乐跑账号登录失效，请重新使用乐跑登录器进行登录'

async function markLoginExpiredByStudentNum(studentNum) {
    const sid = String(studentNum ?? '').trim()
    if (!sid) return
    await db.query(
        'UPDATE lepao_account SET state = 0, update_time = ? WHERE student_num = ?',
        [Date.now(), sid]
    )
}

async function markLoginExpiredByToken(token) {
    const tokenClean = String(token ?? '').trim()
    if (!tokenClean) return
    await db.query(
        'UPDATE lepao_account SET state = 0, update_time = ? WHERE token = ?',
        [Date.now(), tokenClean]
    )
}

/**
 * @param {string} token
 * @param {{ userAgent?: string, deviceModel?: string }} [device]
 * @returns {Promise<
 *   | { ok: false, msg: string, jkesRes?: object }
 *   | {
 *       ok: true
 *       student_num: string
 *       findRows: object[]
 *       profile: {
 *         name: string
 *         academy_name: string
 *         grade_id: any
 *         class_id: any
 *         sex: number
 *         user_avatar: string
 *       }
 *     }
 * >}
 */
async function syncLepaoAccountFromToken(token, device = {}) {
    let jkesRes
    try {
        jkesRes = await jkesRequest('/sys/user/getMyInfo', {}, token)
    } catch (error) {
        if (error?.loginExpired) {
            await markLoginExpiredByToken(token)
            return {
                ok: false,
                msg: LOGIN_EXPIRED_MSG
            }
        }
        throw error
    }

    if (!jkesRes || jkesRes.code !== 0 || !jkesRes.data || !jkesRes.data.info) {
        return {
            ok: false,
            msg: jkesRes?.message || '获取用户信息失败，请稍后重试或联系客服',
            jkesRes
        }
    }

    const {
        code,
        realName,
        identifyCode,
        mobileNumber,
        gender,
        gradeYear,
        collegeCode,
        classCode,
        homeAddr
    } = jkesRes.data.info

    const sex = gender?.label === '男' ? 1 : 2
    const name = realName
    const academy_name = collegeCode?.name ?? ''
    const grade_id = gradeYear
    const class_id = classCode?.className ?? ''
    const student_num = code
    const findSql = `
        SELECT 
            a.email, a.user_avatar, a.create_user, a.auto_run, a.auto_day, a.notice_type, a.target_count,
            a.auto_run_distance_min_km, a.auto_run_distance_max_km, a.pace_min_sec_per_km, a.pace_max_sec_per_km,
            e.bot_umo
        FROM
            lepao_account a
        LEFT JOIN
            lepao_extra e
        ON
            a.student_num = e.student_num
        WHERE
            a.student_num = ? AND a.create_user IS NOT NULL
        `

    const findRows = await db.query(findSql, [student_num])
    if (!findRows) {
        return { ok: false, msg: '无法获取用户数据，请重试' }
    }
    if (findRows.length === 0) {
        return {
            ok: false,
            msg: '该乐跑账号尚未在沐晨乐跑中添加，请先前往 https://jkes.xxoo365.top/ 添加你的账户'
        }
    }

    const user_avatar =
        resolveQQAvatarFromEmail(findRows[0].email) ||
        findRows[0].user_avatar ||
        DEFAULT_AVATAR

    const time = Date.now()
    const ua = device.userAgent
    const dm = device.deviceModel

    let updateSql =
        'UPDATE lepao_account SET token = ?, name = ?, grade_id = ?, class_id = ?, sex = ?, academy_name = ?, update_time = ?, user_avatar = ?, identifyCode = ?, mobileNumber = ?, homeAddr = ?, state = 1'
    const params = [
        token,
        name,
        grade_id,
        class_id,
        sex,
        academy_name,
        time,
        user_avatar,
        identifyCode,
        mobileNumber,
        homeAddr
    ]

    if (ua != null && ua !== '') {
        updateSql += ', userAgent = ?'
        params.push(ua)
    }
    if (dm != null && dm !== '') {
        updateSql += ', deviceModel = ?'
        params.push(dm)
    }

    updateSql += ' WHERE student_num = ?'
    params.push(student_num)

    const updateRows = await db.query(updateSql, params)
    if (!updateRows || updateRows.affectedRows < 1) {
        return { ok: false, msg: '更新账号信息失败，请重试' }
    }

    return {
        ok: true,
        student_num,
        findRows,
        profile: {
            name,
            academy_name,
            grade_id,
            class_id,
            sex,
            user_avatar
        }
    }
}

module.exports = {
    syncLepaoAccountFromToken,
    markLoginExpiredByStudentNum,
    markLoginExpiredByToken,
    LOGIN_EXPIRED_MSG,
    DEFAULT_AVATAR
}
