const express = require('express');
const router = express.Router();
const authorize = require('../../../../middlewares/authorize-sapps');
const masterListService = require('./masterList.service');
const redisClient = require('../../../../redisClient');

router.get('/', authorize(), getAll);
router.get('/from-mapping', authorize(), getAllFromMapping);
router.get('/filter', authorize(), filter);
router.get("/get-mapping", authorize(), getFromMapping);
router.post('/territory', authorize(), getByTerritoriId);
router.post('/store-masterlists', authorize(), storeToMasterLists);
router.post('/store-masterlist', authorize(), storeToMasterList); // satuan
router.post('/create', authorize(), create);
router.delete('/:id', authorize(), _delete);

module.exports = router;

async function getAll(req, res, next) {
    try {
        // Membuat cacheKey berdasarkan req.query
        const cacheKey = `statuses:${JSON.stringify(req.query)}-masterlists`;

        // Mengecek apakah data sudah ada di Redis
        const cachedData = await redisClient.get(cacheKey);
        if (cachedData) {
            return res.json(JSON.parse(cachedData));
        }

        // Jika tidak ada, panggil masterListService.getAll(req.query)
        const result = await masterListService.getAll(req.query);

        // Simpan hasilnya ke Redis dengan expire time misalnya 60 detik
        await redisClient.setEx(cacheKey, 60, JSON.stringify(result));

        // Kembalikan response JSON dari hasil panggilan service
        return res.json(result);
    } catch (error) {
        return next(error);
    }
}

// function getAll(req, res, next) {
//     masterListService.getAll()
//         .then(result => res.json(result))
//         .catch(next);
// }

function getAllFromMapping(req, res, next) {
    masterListService.getAllFromMapping()
        .then(result => res.json(result))
        .catch(next);
}


function getFromMapping(req, res, next) {
    masterListService
    .getFromMapping(req.query)
    .then((result) => res.json(result))
    .catch(next);
}

function getByTerritoriId(req, res, next) {
    masterListService
    .getByTerritoriId(req.body)
    .then((result) => res.json(result))
    .catch(next);
}

function filter(req, res, next) {
    masterListService.filter(req.query)
        .then(result => res.json(result))
        .catch(next);
}

function storeToMasterLists(req, res, next) {
    masterListService.storeToMasterLists(req.body)
        .then(result => res.json(result))
        .catch(next);
}

function storeToMasterList(req, res, next) {
    masterListService.storeToMasterList(req.body)
        .then(result => res.json(result))
        .catch(next);
}

function create(req, res, next) {
    masterListService.assignMasterList(req.body)
        .then(result => res.json(result))
        .catch(next);
}

function _delete(req, res, next) {
    masterListService.deleteMasterLists(req.params.id)
        .then(result => res.json(result))
        .catch(next);
}
