const express = require('express');
const router = express.Router();
const db = require('../config/db');

// GET all leads
router.get('/', async (req, res, next) => {
  try {
    const leads = await db.getAllLeads();
    res.json({ success: true, leads });
  } catch (error) {
    next(error);
  }
});

// GET single lead by ID
router.get('/:id', async (req, res, next) => {
  try {
    const lead = await db.getLeadById(req.params.id);
    if (!lead) return res.status(404).json({ success: false, message: 'Lead not found' });
    res.json({ success: true, lead });
  } catch (error) {
    next(error);
  }
});

// POST create a new lead
router.post('/', async (req, res, next) => {
  try {
    const lead = await db.createLead(req.body);
    res.status(201).json({ success: true, lead });
  } catch (error) {
    next(error);
  }
});

// PUT update lead details
router.put('/:id', async (req, res, next) => {
  try {
    const updated = await db.updateLead(req.params.id, req.body);
    if (!updated) return res.status(404).json({ success: false, message: 'Lead not found' });
    res.json({ success: true, message: 'Lead updated successfully' });
  } catch (error) {
    next(error);
  }
});

// POST assign users to lead
router.post('/:id/assign', async (req, res, next) => {
  try {
    const { user_ids } = req.body;
    if (!Array.isArray(user_ids)) {
      return res.status(400).json({ success: false, message: 'user_ids must be an array' });
    }
    await db.assignUsersToLead(req.params.id, user_ids);
    res.json({ success: true, message: 'Users assigned successfully' });
  } catch (error) {
    next(error);
  }
});

// POST add conversation log
router.post('/:id/conversations', async (req, res, next) => {
  try {
    // req.body should contain { user_id, type, message, next_followup_date, status }
    const { user_id } = req.body;
    if (!user_id) return res.status(400).json({ success: false, message: 'user_id is required' });
    
    await db.addLeadConversation(req.params.id, user_id, req.body);
    res.status(201).json({ success: true, message: 'Conversation logged successfully' });
  } catch (error) {
    next(error);
  }
});

module.exports = router;
