const express = require('express');
const { requireCapability } = require('../middleware/auth');
const {
  addPhoto,
  createPart,
  deletePart,
  deletePhoto,
  deleteStock,
  getPart,
  listParts,
  recordTransaction,
  saveStock,
  updatePart
} = require('../services/parts');

const router = express.Router();
const editor = requireCapability('parts.manage');

router.get('/parts', (req, res) => {
  res.json({ parts: listParts(req.query, req.companyId) });
});

router.get('/parts/:id', (req, res) => {
  const part = getPart(req.params.id, req.companyId);
  if (!part) return res.status(404).json({ error: 'Part not found' });
  return res.json({ part });
});

router.post('/parts', editor, (req, res) => {
  res.status(201).json({ part: createPart(req.body, req.user.id, req.companyId) });
});

router.put('/parts/:id', editor, (req, res) => {
  const part = updatePart(req.params.id, req.body, req.user.id, req.companyId);
  if (!part) return res.status(404).json({ error: 'Part not found' });
  return res.json({ part });
});

router.delete('/parts/:id', requireCapability('parts.manage'), (req, res) => {
  if (!deletePart(req.params.id, req.user.id, req.companyId)) return res.status(404).json({ error: 'Part not found' });
  return res.status(204).end();
});

// Stock locations (aisle/bin + on-hand/reserved per location)
router.post('/parts/:id/stock', editor, (req, res) => {
  const part = saveStock(req.params.id, req.body, req.user.id, req.companyId);
  if (!part) return res.status(404).json({ error: 'Part or stock location not found' });
  return res.status(201).json({ part });
});

router.delete('/parts/:id/stock/:stockId', editor, (req, res) => {
  const part = deleteStock(req.params.id, req.params.stockId, req.user.id, req.companyId);
  if (!part) return res.status(404).json({ error: 'Stock location not found' });
  return res.json({ part });
});

// Stock movements (receive/issue/adjust/reserve/unreserve)
router.post('/parts/:id/transactions', editor, (req, res) => {
  const part = recordTransaction(req.params.id, req.body, req.user.id, req.companyId);
  if (!part) return res.status(404).json({ error: 'Part not found' });
  return res.status(201).json({ part });
});

// Photos
router.post('/parts/:id/photos', editor, (req, res) => {
  const part = addPhoto(req.params.id, req.body, req.user.id, req.companyId);
  if (!part) return res.status(404).json({ error: 'Part not found' });
  return res.status(201).json({ part });
});

router.delete('/parts/:id/photos/:photoId', editor, (req, res) => {
  const part = deletePhoto(req.params.id, req.params.photoId, req.user.id, req.companyId);
  if (!part) return res.status(404).json({ error: 'Photo not found' });
  return res.json({ part });
});

module.exports = router;
