import { Router } from 'express';
import { emailService } from '../services/EmailService.js';

const router = Router();

router.get('/', (_req, res) => {
  res.json(emailService.getAll());
});

router.get('/:id', (req, res) => {
  const mail = emailService.getById(req.params.id);
  if (!mail) {
    res.status(404).json({ error: 'Mail not found' });
    return;
  }

  res.json(mail);
});

router.post('/:id/read', (req, res) => {
  try {
    emailService.markRead(req.params.id);
    res.json({ ok: true });
  } catch (error) {
    const statusCode = error.statusCode ?? 500;
    res.status(statusCode).json({ error: error.message });
  }
});

router.post('/:id/reply', (req, res) => {
  const rawChoice = req.body?.choice;
  if (!Number.isInteger(rawChoice)) {
    res.status(400).json({ error: 'choice must be an integer' });
    return;
  }

  const choice = Number(rawChoice);

  try {
    const result = emailService.reply(req.params.id, choice);
    res.json(result);
  } catch (error) {
    const statusCode = error.statusCode ?? 500;
    res.status(statusCode).json({ error: error.message });
  }
});

export default router;
