const express = require('express');
const { requireCapability } = require('../middleware/auth');
const {
  addNote,
  createContact,
  deleteContact,
  deleteNote,
  getContact,
  listContacts,
  updateContact
} = require('../services/contacts');

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

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

router.get('/contacts/:id', (req, res) => {
  const contact = getContact(req.params.id, req.companyId);
  if (!contact) return res.status(404).json({ error: 'Contact not found' });
  return res.json({ contact });
});

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

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

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

router.post('/contacts/:id/notes', editor, (req, res) => {
  if (!req.body.body) return res.status(400).json({ error: 'Note body is required' });
  const note = addNote(req.params.id, req.body.body, req.user.id, req.companyId);
  if (!note) return res.status(404).json({ error: 'Contact not found' });
  return res.status(201).json({ note });
});

router.delete('/contacts/:id/notes/:noteId', editor, (req, res) => {
  if (!deleteNote(req.params.id, req.params.noteId, req.user.id, req.companyId)) return res.status(404).json({ error: 'Note not found' });
  return res.status(204).end();
});

module.exports = router;
