const LeadService = require('../services/leadService');
const logger = require('../utils/logger');
const { ApiError } = require('../utils/apiError');

class LeadController {
  static async create(req, res, next) {
    try {
      const validatedData = await Lead.validateLead(req.body);
      const lead = await LeadService.create(validatedData);
      logger.info('Lead created successfully', { leadId: lead.id });
      res.status(201).json({
        success: true,
        data: lead
      });
    } catch (error) {
      logger.error('Error creating lead', { error: error.message });
      next(new ApiError(error.message, 400));
    }
  }

  static async getAll(req, res, next) {
    try {
      const { page = 1, limit = 10, status } = req.query;
      const leads = await LeadService.getAll({ page, limit, status });
      res.json({
        success: true,
        data: leads.rows,
        pagination: {
          total: leads.count,
          page: parseInt(page),
          pages: Math.ceil(leads.count / limit)
        }
      });
    } catch (error) {
      logger.error('Error fetching leads', { error: error.message });
      next(new ApiError(error.message, 500));
    }
  }

  static async getById(req, res, next) {
    try {
      const lead = await LeadService.getById(req.params.id);
      if (!lead) {
        throw new ApiError('Lead not found', 404);
      }
      res.json({
        success: true,
        data: lead
      });
    } catch (error) {
      logger.error('Error fetching lead', { error: error.message, leadId: req.params.id });
      next(error);
    }
  }

  static async update(req, res, next) {
    try {
      const validatedData = await Lead.validateLead(req.body);
      const lead = await LeadService.update(req.params.id, validatedData);
      if (!lead) {
        throw new ApiError('Lead not found', 404);
      }
      logger.info('Lead updated successfully', { leadId: lead.id });
      res.json({
        success: true,
        data: lead
      });
    } catch (error) {
      logger.error('Error updating lead', { error: error.message, leadId: req.params.id });
      next(error);
    }
  }

  static async delete(req, res, next) {
    try {
      await LeadService.delete(req.params.id);
      logger.info('Lead deleted successfully', { leadId: req.params.id });
      res.status(204).send();
    } catch (error) {
      logger.error('Error deleting lead', { error: error.message, leadId: req.params.id });
      next(error);
    }
  }
}