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

class GetMySendCountRequestList extends API {
    constructor() {
        super()
        this.setPath("/Goods/SendCountRequest/MyList")
        this.setMethod("GET")
    }

    async onRequest(req, res) {
        let { uuid, session, pagesize, current, direction, status } = req.query

        if ([uuid, session, pagesize, current].some(value => value === "" || value === null || value === undefined))
            return res.json({ ...BaseStdResponse.MISSING_PARAMETER })

        if (isNaN(pagesize) || pagesize <= 0 || pagesize > 50 || isNaN(current) || current <= 0)
            return res.json({ ...BaseStdResponse.ERR, msg: "参数错误" })

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

        const directionList = ["sent", "received"]
        if (direction && !directionList.includes(direction))
            return res.json({ ...BaseStdResponse.ERR, msg: "direction参数错误" })

        const statusList = ["pending", "approved", "rejected"]
        if (status && !statusList.includes(status))
            return res.json({ ...BaseStdResponse.ERR, msg: "status参数错误" })

        const userRows = await db.query("SELECT id FROM users WHERE uuid = ?", [uuid])
        if (!userRows || userRows.length !== 1)
            return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "获取用户信息失败！" })

        const userId = userRows[0].id
        const offset = (Number(current) - 1) * Number(pagesize)

        let sql = `
            SELECT
                r.id,
                r.sender_uuid,
                su.username AS sender_username,
                su.avatar AS sender_avatar,
                r.receiver_user_id,
                ru.username AS receiver_username,
                ru.avatar AS receiver_avatar,
                CASE WHEN r.sender_uuid = ? THEN 'sent' ELSE 'received' END AS direction,
                CASE WHEN r.sender_uuid = ? THEN ru.username ELSE su.username END AS counterparty_username,
                CASE WHEN r.sender_uuid = ? THEN ru.avatar ELSE su.avatar END AS counterparty_avatar,
                r.count,
                r.status,
                r.created_at,
                r.reviewed_at,
                r.reject_reason
            FROM
                lepao_send_count_request r
            LEFT JOIN users su ON su.uuid = r.sender_uuid
            LEFT JOIN users ru ON ru.id = r.receiver_user_id
            WHERE
                (r.sender_uuid = ? OR r.receiver_user_id = ?)
        `

        let countSql = `
            SELECT COUNT(*) AS total
            FROM
                lepao_send_count_request r
            WHERE
                (r.sender_uuid = ? OR r.receiver_user_id = ?)
        `

        const params = [uuid, uuid, uuid, uuid, userId]
        const countParams = [uuid, userId]

        if (direction === "sent") {
            sql += ` AND r.sender_uuid = ?`
            countSql += ` AND r.sender_uuid = ?`
            params.push(uuid)
            countParams.push(uuid)
        }

        if (direction === "received") {
            sql += ` AND r.receiver_user_id = ?`
            countSql += ` AND r.receiver_user_id = ?`
            params.push(userId)
            countParams.push(userId)
        }

        if (status) {
            sql += ` AND r.status = ?`
            countSql += ` AND r.status = ?`
            params.push(status)
            countParams.push(status)
        }

        sql += `
            ORDER BY r.id DESC
            LIMIT ? OFFSET ?
        `
        params.push(String(pagesize), String(offset))

        const rows = await db.query(sql, params)
        const countRows = await db.query(countSql, countParams)

        if (!rows || !countRows)
            return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "获取赠送记录失败！" })

        res.json({
            ...BaseStdResponse.OK,
            data: rows,
            pagination: {
                current: Number(current),
                pagesize: Number(pagesize),
                total: countRows[0]?.total || 0
            }
        })
    }
}

module.exports.GetMySendCountRequestList = GetMySendCountRequestList
