import db from '../config/database.js';
import { v4 as uuidv4 } from 'uuid';

export const getRemarks = async (req, res) => {
  try {
    const [remarks] = await db.query(
      'SELECT * FROM remarks WHERE customer_id = ? ORDER BY created_at DESC',
      [req.params.customerId]
    );
    res.json(remarks);
  } catch (error) {
    console.error('Get remarks error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const createRemark = async (req, res) => {
  try {
    const { remark_text } = req.body;
    const { customerId } = req.params;
    const remarkId = uuidv4();

    await db.query(
      'INSERT INTO remarks (id, customer_id, salesman_id, remark_text) VALUES (?, ?, ?, ?)',
      [remarkId, customerId, req.user.id, remark_text]
    );

    const [remark] = await db.query('SELECT * FROM remarks WHERE id = ?', [remarkId]);

    res.status(201).json({
      message: 'Remark added successfully',
      remark: remark[0]
    });
  } catch (error) {
    console.error('Create remark error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const getMeetings = async (req, res) => {
  try {
    const [meetings] = await db.query(
      'SELECT * FROM meetings WHERE customer_id = ? ORDER BY meeting_date DESC',
      [req.params.customerId]
    );
    res.json(meetings);
  } catch (error) {
    console.error('Get meetings error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const createMeeting = async (req, res) => {
  try {
    const { meeting_date, discussion_notes, outcome } = req.body;
    const { customerId } = req.params;
    const meetingId = uuidv4();

    await db.query(
      'INSERT INTO meetings (id, customer_id, salesman_id, meeting_date, discussion_notes, outcome) VALUES (?, ?, ?, ?, ?, ?)',
      [meetingId, customerId, req.user.id, meeting_date, discussion_notes, outcome]
    );

    const [meeting] = await db.query('SELECT * FROM meetings WHERE id = ?', [meetingId]);

    res.status(201).json({
      message: 'Meeting added successfully',
      meeting: meeting[0]
    });
  } catch (error) {
    console.error('Create meeting error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const getFollowUps = async (req, res) => {
  try {
    const [followUps] = await db.query(
      'SELECT * FROM follow_ups WHERE customer_id = ? ORDER BY scheduled_date ASC',
      [req.params.customerId]
    );
    res.json(followUps);
  } catch (error) {
    console.error('Get follow-ups error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const getAllFollowUps = async (req, res) => {
  try {
    const [followUps] = await db.query(
      `SELECT f.*, c.full_name as customer_name, c.email as customer_email,
       p.full_name as salesman_name
       FROM follow_ups f
       JOIN customers c ON f.customer_id = c.id
       JOIN profiles p ON f.salesman_id = p.id
       ORDER BY f.scheduled_date ASC`
    );
    res.json(followUps);
  } catch (error) {
    console.error('Get all follow-ups error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const getMyFollowUps = async (req, res) => {
  try {
    const [followUps] = await db.query(
      'SELECT f.*, c.full_name as customer_name, c.email as customer_email FROM follow_ups f JOIN customers c ON f.customer_id = c.id WHERE f.salesman_id = ? AND f.completed = FALSE ORDER BY f.scheduled_date ASC',
      [req.user.id]
    );
    res.json(followUps);
  } catch (error) {
    console.error('Get my follow-ups error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const createFollowUp = async (req, res) => {
  try {
    const { scheduled_date, purpose } = req.body;
    const { customerId } = req.params;
    const followUpId = uuidv4();

    await db.query(
      'INSERT INTO follow_ups (id, customer_id, salesman_id, scheduled_date, purpose) VALUES (?, ?, ?, ?, ?)',
      [followUpId, customerId, req.user.id, scheduled_date, purpose]
    );

    const [followUp] = await db.query('SELECT * FROM follow_ups WHERE id = ?', [followUpId]);

    res.status(201).json({
      message: 'Follow-up scheduled successfully',
      followUp: followUp[0]
    });
  } catch (error) {
    console.error('Create follow-up error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const updateFollowUp = async (req, res) => {
  try {
    const { completed } = req.body;
    const { id } = req.params;

    await db.query('UPDATE follow_ups SET completed = ? WHERE id = ?', [completed, id]);

    const [followUp] = await db.query('SELECT * FROM follow_ups WHERE id = ?', [id]);

    res.json({
      message: 'Follow-up updated successfully',
      followUp: followUp[0]
    });
  } catch (error) {
    console.error('Update follow-up error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};
