const router = require('express').Router();
const pool = require('../config/db');
const auth = require('../middleware/auth');
const { requireRole } = require('../middleware/auth');
const { uid } = require('../models/helpers');
const { createNotification } = require('../models/notifications');

router.use(auth);
router.use(requireRole('master_admin', 'cashier'));

// Get all follow-ups with order & client info
router.get('/', async (req, res) => {
  try {
    const [rows] = await pool.query(`
      SELECT f.*, o.client_id, o.id as order_id
      FROM follow_ups f
      JOIN orders o ON f.order_id = o.id
      ORDER BY f.follow_date ASC
    `);
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Create follow-up
router.post('/', async (req, res) => {
  try {
    const id = uid();
    const { order_id, follow_date, note } = req.body;
    await pool.query(
      'INSERT INTO follow_ups (id, order_id, follow_date, note, status, sent) VALUES (?, ?, ?, ?, ?, 0)',
      [id, order_id, follow_date, note || '', 'pending']
    );
    const [rows] = await pool.query('SELECT * FROM follow_ups WHERE id = ?', [id]);
    await createNotification(pool, { type: 'follow_up', action: 'created', title: 'Follow-up Created', message: `Follow-up scheduled for ${follow_date}`, detail: { followUp: rows[0] }, entity: 'follow_up', entityId: id, triggeredBy: req.user.id });
    res.status(201).json(rows[0]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Mark follow-up as sent/done
router.put('/:id/mark-sent', async (req, res) => {
  try {
    await pool.query("UPDATE follow_ups SET status = 'done', sent = 1 WHERE id = ?", [req.params.id]);
    const [rows] = await pool.query('SELECT * FROM follow_ups WHERE id = ?', [req.params.id]);
    await createNotification(pool, { type: 'follow_up', action: 'completed', title: 'Follow-up Completed', message: `Follow-up marked as done`, detail: { followUp: rows[0] }, entity: 'follow_up', entityId: req.params.id, triggeredBy: req.user.id });
    res.json(rows[0]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
