'use strict';

const express = require('express');
const router = express.Router();
const svc = require('../services/comprasService');
const { noNulls } = require('../utils/noNulls');
const { requirePermission } = require('../middleware/permissions');

const ok = (res, data) => res.json({ ok: true, data: noNulls(data) });
const err = (res, e, status = 400) => res.status(status).json({
  ok: false,
  error: process.env.NODE_ENV === 'production' ? 'Error interno del servidor' : e.message,
});

const requireEscritor = requirePermission('compras.sync.view');

router.get('/proveedores', async (_req, res) => {
  try { ok(res, await svc.getProveedores()); } catch (e) { err(res, e); }
});

router.post('/proveedores', requireEscritor, async (req, res) => {
  try { ok(res, await svc.crearProveedor(req.body)); } catch (e) { err(res, e); }
});

router.get('/presentaciones', async (_req, res) => {
  try { ok(res, await svc.getPresentaciones()); } catch (e) { err(res, e); }
});

router.get('/almacenes', async (_req, res) => {
  try { ok(res, await svc.getAlmacenes()); } catch (e) { err(res, e); }
});

router.get('/', async (req, res) => {
  try {
    const { desde, hasta, idproveedor } = req.query;
    ok(res, await svc.getCompras({ desde, hasta, idproveedor }));
  } catch (e) { err(res, e); }
});

router.get('/conciliacion/stock', async (req, res) => {
  try {
    const { idalmacen } = req.query;
    ok(res, await svc.getStockActual(idalmacen));
  } catch (e) { err(res, e); }
});

router.post('/conciliacion', requireEscritor, async (req, res) => {
  try {
    const usuario = req.user?.nombre || req.user?.usuario || 'ARKHON';
    const { ajustes } = req.body || {};
    ok(res, await svc.guardarConciliacion(ajustes, usuario));
  } catch (e) { err(res, e); }
});

router.get('/:idcompra/detalle', async (req, res) => {
  try { ok(res, await svc.getDetalleCompra(req.params.idcompra)); } catch (e) { err(res, e); }
});

router.post('/', requireEscritor, async (req, res) => {
  try {
    const usuario = req.user?.nombre || req.user?.usuario || req.user?.tipo || 'ARKHON';
    ok(res, await svc.crearCompra(req.body, usuario));
  } catch (e) { err(res, e); }
});

router.post('/:idcompra/cancelar', requireEscritor, async (req, res) => {
  try {
    const usuario = req.user?.nombre || req.user?.usuario || 'ARKHON';
    ok(res, await svc.cancelarCompra(req.params.idcompra, usuario));
  } catch (e) { err(res, e); }
});

module.exports = router;
