'use strict';
const httpStatus = require('http-status');
const Sequelize = require('sequelize');
const generateControllers = require('../../core/controllers');
const { buildContext } = require('../../core/controllers');
const pushService = require('./push.service');
const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper');

// Module Name
const MODULE_NAME = '[push.controller]';
const controllerOptions = { MODULE_NAME };

const extraControllers = {
    createOrUpdate: (config) => {
        return async (req, res, next) => {
            try {
                const context = buildContext(req, config);
                var data = {
                    token: req.body.token,
                    valid: 1,
                    userId: context.user.id
                };

                let params = extractParamsFromRequest(req, res, { 
                    includeAll: false, 
                    paginate: { limit: 1, page: 1 },
                    params: {
                        userId: context.user.id,
                        token: data.token,
                    }
                });

                // Buscamos el token y el usuario
                let result = await pushService.fetchOne(params, context);
                if (!result) {
                    // Dar de alta el token
                    console.log('>> Dar de alta el token');
                    result = await pushService.create(data, context);
                } else {
                    // Actualizar el token
                    console.log('>> Actualizar el token');
                    result = await pushService.update(params.params, data, context);
                }
            } catch(error) {
                console.error(error);
            } finally {
                // En todo caso devolver OK al cliente
                return handleResultResponse('OK', null, null, res, httpStatus.OK);    
            }
        }
    },    
};

module.exports = generateControllers(pushService, extraControllers, controllerOptions);