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

router.use(auth);

// Get all clients (all roles)
router.get('/', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM clients ORDER BY name');
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Get single client (all roles)
router.get('/:id', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM clients WHERE id = ?', [req.params.id]);
    if (rows.length === 0) return res.status(404).json({ error: 'Client not found' });
    res.json(rows[0]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Create client (master_admin, cashier)
router.post('/', requireRole('master_admin', 'cashier'), async (req, res) => {
  try {
    const id = uid();
    const { name, phone, email, address, allergies, notes, birth_date, is_vip, referred_by } = req.body;

    if (phone) {
      const [dup] = await pool.query('SELECT id FROM clients WHERE phone = ? AND is_deleted = 0', [phone]);
      if (dup.length > 0) return res.status(400).json({ error: 'Phone number already exists' });
    }
    if (email) {
      const [dup] = await pool.query('SELECT id FROM clients WHERE email = ? AND is_deleted = 0', [email]);
      if (dup.length > 0) return res.status(400).json({ error: 'Email already exists' });
    }

    await pool.query(
      'INSERT INTO clients (id, name, phone, email, address, allergies, notes, birth_date, is_deleted, is_vip, referred_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)',
      [id, name, phone || '', email || '', address || '', allergies || '', notes || '', birth_date || null, is_vip ? 1 : 0, referred_by || null]
    );
    await logActivity(pool, 'create', 'client', id, name);
    const [rows] = await pool.query('SELECT * FROM clients WHERE id = ?', [id]);
    await createNotification(pool, { type: 'client', action: 'created', title: 'Client Added', message: `${name} was added`, detail: { client: rows[0] }, entity: 'client', entityId: id, triggeredBy: req.user.id });
    res.status(201).json(rows[0]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Update client (master_admin, cashier)
router.put('/:id', requireRole('master_admin', 'cashier'), async (req, res) => {
  try {
    const { name, phone, email, address, allergies, notes, birth_date, referred_by } = req.body;

    if (phone) {
      const [dup] = await pool.query('SELECT id FROM clients WHERE phone = ? AND id != ? AND is_deleted = 0', [phone, req.params.id]);
      if (dup.length > 0) return res.status(400).json({ error: 'Phone number already exists' });
    }
    if (email) {
      const [dup] = await pool.query('SELECT id FROM clients WHERE email = ? AND id != ? AND is_deleted = 0', [email, req.params.id]);
      if (dup.length > 0) return res.status(400).json({ error: 'Email already exists' });
    }

    await pool.query(
      'UPDATE clients SET name=?, phone=?, email=?, address=?, allergies=?, notes=?, birth_date=?, referred_by=? WHERE id=?',
      [name, phone, email, address, allergies, notes, birth_date || null, referred_by || null, req.params.id]
    );
    await logActivity(pool, 'edit', 'client', req.params.id, name);
    const [rows] = await pool.query('SELECT * FROM clients WHERE id = ?', [req.params.id]);
    await createNotification(pool, { type: 'client', action: 'edited', title: 'Client Updated', message: `${name}'s info was updated`, detail: { client: rows[0] }, entity: 'client', entityId: req.params.id, triggeredBy: req.user.id });
    res.json(rows[0]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Soft delete client (master_admin only)
router.delete('/:id', requireRole('master_admin'), async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM clients WHERE id = ?', [req.params.id]);
    if (rows.length === 0) return res.status(404).json({ error: 'Not found' });
    await pool.query('UPDATE clients SET is_deleted = 1 WHERE id = ?', [req.params.id]);
    await logActivity(pool, 'delete', 'client', req.params.id, rows[0].name, JSON.stringify({ t: 'client_del', id: req.params.id }));
    await createNotification(pool, { type: 'client', action: 'deleted', title: 'Client Deleted', message: `${rows[0].name} was deleted`, detail: { client: rows[0] }, entity: 'client', entityId: req.params.id, triggeredBy: req.user.id });
    res.json({ message: 'Client deleted' });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Restore client (master_admin only)
router.put('/:id/restore', requireRole('master_admin'), async (req, res) => {
  try {
    await pool.query('UPDATE clients SET is_deleted = 0 WHERE id = ?', [req.params.id]);
    await logActivity(pool, 'restore', 'client', req.params.id);
    const [rows] = await pool.query('SELECT * FROM clients WHERE id = ?', [req.params.id]);
    res.json(rows[0]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Toggle VIP (master_admin, cashier)
router.put('/:id/toggle-vip', requireRole('master_admin', 'cashier'), async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM clients WHERE id = ?', [req.params.id]);
    if (rows.length === 0) return res.status(404).json({ error: 'Not found' });
    const newVip = rows[0].is_vip ? 0 : 1;
    await pool.query('UPDATE clients SET is_vip = ? WHERE id = ?', [newVip, req.params.id]);
    await logActivity(pool, 'vip', 'client', req.params.id, newVip ? 'VIP granted' : 'VIP removed');
    const [updated] = await pool.query('SELECT * FROM clients WHERE id = ?', [req.params.id]);
    await createNotification(pool, { type: 'client', action: 'vip_toggled', title: newVip ? 'VIP Granted' : 'VIP Removed', message: `${rows[0].name} ${newVip ? 'is now VIP' : 'VIP status removed'}`, detail: { client: updated[0] }, entity: 'client', entityId: req.params.id, triggeredBy: req.user.id });
    res.json(updated[0]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
