const express = require('express');
const router = express.Router();
const globalService = require('../services/globalService');
const intermediaireService = require('../services/intermediaireService');
const logger = require('../utils/logger');

router.get('/read/:numPortefeuille', async (req, res) => {
    const numPortefeuille = req.params.numPortefeuille;
    const idIntermediaire = await globalService.getRecordIdFromFieldValue("intermediaire", "numPortefeuille", numPortefeuille);

    if (idIntermediaire) {
        res.json({ valid: true, idIntermediaire });
    } else {
        res.json({ valid: false });
    }
});

router.post('/create', async (req, res) => {
    const intermediaire = await intermediaireService.createIntermediaire();

    res.json({ valid: Boolean(intermediaire), intermediaire });
});

router.post('/update/:idIntermediaire', async (req, res) => {
    const idIntermediaire = req.params.idIntermediaire;
    const data = req.body;
    const record = await globalService.updateRecordFromData("intermediaire", idIntermediaire, data);
    
    res.json({ valid: Boolean(record)});
});

module.exports = router;