const express = require('express');
const {
  getOrganigramaCompleto,
  createNodo,
  updateNodo,
  deleteNodo,
  listDepartamentosOptions,
} = require('../config/database');
const { NIVEL_KEYS } = require('../config/organizacionDefaults');

const router = express.Router();

router.get('/departamentos', (_req, res) => {
  try {
    res.json({ success: true, data: listDepartamentosOptions() });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

router.get('/', (_req, res) => {
  try {
    res.json({ success: true, data: getOrganigramaCompleto() });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

router.get('/niveles', (_req, res) => {
  res.json({ success: true, data: NIVEL_KEYS });
});

router.post('/nodos', (req, res) => {
  try {
    const nodo = createNodo(req.body);
    res.status(201).json({ success: true, data: { nodo, organigrama: getOrganigramaCompleto() } });
  } catch (error) {
    res.status(400).json({ success: false, error: error.message });
  }
});

router.put('/nodos/:id', (req, res) => {
  try {
    const nodo = updateNodo(req.params.id, req.body);
    res.json({ success: true, data: { nodo, organigrama: getOrganigramaCompleto() } });
  } catch (error) {
    res.status(400).json({ success: false, error: error.message });
  }
});

router.delete('/nodos/:id', (req, res) => {
  try {
    deleteNodo(req.params.id);
    res.json({ success: true, data: getOrganigramaCompleto() });
  } catch (error) {
    res.status(400).json({ success: false, error: error.message });
  }
});

module.exports = router;
