const API = require("../../lib/API.js")
const db = require('../../plugin/DataBase/db')
const Redis = require('../../plugin/DataBase/Redis')
const { BaseStdResponse } = require("../../BaseStdResponse")

class ResetMonthTermNum extends API {
    constructor() {
        super()
        this.noEncrypt()
        this.setPath('/Corn/ResetMonthTermNum')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        try {
            res.json({
                ...BaseStdResponse.OK
            })

            // 1) 清空所有账号本月累计里程（term_num）
            const r = await db.query('UPDATE lepao_account SET term_num = 0')
            if (!r) {
                this.logger.error('月初重置 term_num 失败：数据库更新失败')
                return
            }

            // 2) 清理 Redis 当月缓存（jkes_month:{student}:{YYYY-MM}）
            const now = new Date()
            const y = now.getFullYear()
            const m = String(now.getMonth() + 1).padStart(2, '0')
            const pattern = `jkes_month:*:${y}-${m}`

            try {
                const toDel = []
                for await (const key of Redis.scanIterator({ MATCH: pattern, COUNT: 500 })) {
                    toDel.push(key)
                    if (toDel.length >= 500) {
                        await Redis.del(toDel)
                        toDel.length = 0
                    }
                }
                if (toDel.length) {
                    await Redis.del(toDel)
                }
            } catch (e) {
                this.logger.warn(`月初清理 Redis 月缓存失败：${e.message || e}`)
            }

            this.logger.info(`月初重置完成：term_num=0，pattern=${pattern}`)
        } catch (error) {
            this.logger.error(error)
        }
    }
}

module.exports.ResetMonthTermNum = ResetMonthTermNum

