const API = require("../../../lib/API.js")
const db = require("../../../plugin/DataBase/db.js")
const AccessControl = require("../../../lib/AccessControl.js")
const { BaseStdResponse } = require("../../../BaseStdResponse.js")
const { fetchJkesMonthKm, fetchJkesTotalKm } = require("../../../plugin/jkes/stats")
const { readState, writeState } = require("../../../plugin/jkes/monthPolicy")

/**
 * 使用库内 JKES token 从官方接口同步本月/累计里程到 lepao_account（term_num / total_num）
 */
class UpdateSelfAccount extends API {
    constructor() {
        super()

        this.setPath('/Lepao/Account/UpdateSelfAccount')
        this.setMethod('POST')
    }

    async onRequest(req, res) {
        const { uuid, session, student_num } = req.body
        const loginExpiredMsg = '乐跑账号登录失效，请重新使用乐跑登录器进行登录'

        if ([uuid, session, student_num].some((v) => v === '' || v === null || v === undefined)) {
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })
        }

        if (!await AccessControl.checkSession(uuid, session)) {
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED
            })
        }

        try {
            const rows = await db.query(
                'SELECT token, state FROM lepao_account WHERE student_num = ? AND create_user = ?',
                [student_num, uuid]
            )
            if (!rows || rows.length !== 1) {
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '未找到该乐跑账号或无权限操作'
                })
            }

            const account = rows[0]
            if (!account.token || String(account.token).trim() === '') {
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '账号未登录，请先在客户端更新 JKES 登录信息'
                })
            }

            const now = new Date()
            const y = now.getFullYear()
            const m = now.getMonth() + 1
            let monthKm
            let totalKm
            try {
                monthKm = await fetchJkesMonthKm(account.token, y, m)
                totalKm = await fetchJkesTotalKm(account.token)
            } catch (error) {
                if (error?.loginExpired) {
                    await db.query(
                        'UPDATE lepao_account SET state = 0, update_time = ? WHERE student_num = ? AND create_user = ?',
                        [Date.now(), student_num, uuid]
                    )
                    return res.json({
                        ...BaseStdResponse.ERR,
                        msg: loginExpiredMsg
                    })
                }
                throw error
            }

            const updateTime = Date.now()
            const updateRows = await db.query(
                'UPDATE lepao_account SET term_num = ?, total_num = ?, state = 1, update_time = ? WHERE student_num = ? AND create_user = ?',
                [monthKm, totalKm, updateTime, student_num, uuid]
            )
            if (!updateRows || updateRows.affectedRows !== 1) {
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR
                })
            }

            const prev = await readState(student_num, now)
            await writeState(student_num, { km: monthKm, doubles: prev.doubles }, now)

            return res.json({
                ...BaseStdResponse.OK,
                data: {
                    term_num: monthKm,
                    total_num: totalKm,
                    state: 1
                }
            })
        } catch (error) {
            this.logger.error(`用户自助同步乐跑账号失败: ${error.stack || error}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '同步失败，请稍后再试'
            })
        }
    }
}

module.exports.UpdateSelfAccount = UpdateSelfAccount
