"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const models_1 = require("./models");
const services_1 = __importDefault(require("../../utils/services"));
const constants_1 = __importDefault(require("../../utils/constants"));
function postRewardConsume(req, res) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const id = req.params.id;
            let rewardHash = yield models_1.RewardHash.findById(id).populate('reward');
            if (!rewardHash) {
                return res.status(404).json({ message: 'QR is invalid' });
            }
            if (rewardHash.isConsumed) {
                return res.status(409).json({ message: 'Reward already claimed' });
            }
            const reward = rewardHash.reward;
            if (!reward) {
                return res.status(404).json({ message: 'reward not found' });
            }
            if (reward.remaining <= 0) {
                return res.status(410).json({ message: 'reward is sold out' });
            }
            if (reward.expiredAt && reward.expiredAt <= new Date()) {
                return res.status(410).json({ message: 'reward is expired' });
            }
            rewardHash.isConsumed = true;
            reward.remaining--;
            if (reward.remaining <= 0) {
                reward.expiredAt = new Date();
            }
            yield reward.save();
            yield rewardHash.save();
            // sending socket
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    const socketPayload = {
                        reward: `${reward._id}`,
                        isExpired: !!reward.expiredAt,
                        remaining: reward.remaining,
                    };
                    for (const key in constants_1.default.sockets) {
                        const sockets = constants_1.default.sockets[key];
                        if (!sockets) {
                            continue;
                        }
                        for (const socket of sockets) {
                            services_1.default.socketNotifyUser({
                                userId: `${socket.data.user._id}`,
                                event: 'reward-consumed',
                                data: `${socket.data.user._id}` === `${rewardHash.user}` ? Object.assign(Object.assign({}, socketPayload), { isConsumedByYou: true }) : socketPayload,
                            });
                        }
                    }
                }
                catch (error) {
                    console.log(error);
                }
            }))();
            return res.json({ message: 'QR is valid' });
        }
        catch (error) {
            console.log(error);
            return res.status(500).json({ message: 'server error' });
        }
    });
}
const controllers = {
    postRewardConsume
};
exports.default = controllers;
