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

class GetMyOrders extends API {
    constructor() {
        super();

        this.setPath('/Order/GetMyOrders')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        let { uuid, session } = req.query

        if ([uuid, session].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 1513126
            })

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

        let sql = `
                SELECT 
                    r.orderId,
                    r.state,
                    r.create_time,
                    r.price,
                    r.pay_type,
                    a.name
                FROM 
                    orders r
                JOIN 
                    goods a
                ON 
                    r.goods_id = a.id
                WHERE 
                    r.create_user = ?
                ORDER BY 
                    r.id DESC

                            `
        let rows = await db.query(sql, [uuid])

        if (!rows)
            return res.json({
                ...BaseStdResponse.DATABASE_ERR
            })

        res.json({
            ...BaseStdResponse.OK,
            data: rows
        })
    }
}

module.exports.GetMyOrders = GetMyOrders;