// src/routes/contact.js
const express = require('express');
const db = require('../db');
const rateLimit = require('../middleware/rateLimit');
const requireAdmin = require('../middleware/requireAdmin');

const router = express.Router();

function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(email || ''));
}

// PUBLIC — submit the contact form
router.post('/', rateLimit({ windowMs: 60_000, max: 5 }), (req, res) => {
  const { name, email, phone, reason, message } = req.body || {};
  if (!name || !String(name).trim()) return res.status(400).json({ error: 'Name is required.' });
  if (!isValidEmail(email)) return res.status(400).json({ error: 'A valid email is required.' });
  if (!message || !String(message).trim()) return res.status(400).json({ error: 'Message is required.' });

  db.prepare(`INSERT INTO messages (name, email, phone, reason, message) VALUES (?, ?, ?, ?, ?)`)
    .run(String(name).trim(), String(email).trim(), phone ? String(phone).trim() : null,
      reason ? String(reason).trim() : null, String(message).trim());

  res.status(201).json({ ok: true, message: 'Thank you — your message has been received. We will reply within 2 business days.' });
});

// ADMIN — list messages (newest first)
router.get('/', requireAdmin, (req, res) => {
  const rows = db.prepare('SELECT * FROM messages ORDER BY created_at DESC').all();
  res.json(rows);
});

// ADMIN — mark read/unread
router.patch('/:id', requireAdmin, (req, res) => {
  const { status } = req.body || {};
  if (!['new', 'read'].includes(status)) return res.status(400).json({ error: 'Invalid status.' });
  db.prepare('UPDATE messages SET status = ? WHERE id = ?').run(status, req.params.id);
  res.json({ ok: true });
});

// ADMIN — delete a message
router.delete('/:id', requireAdmin, (req, res) => {
  db.prepare('DELETE FROM messages WHERE id = ?').run(req.params.id);
  res.json({ ok: true });
});

module.exports = router;
