import { Request, Response } from 'express';
import { AuthRequest } from '../middleware/auth';
import * as leadService from '../services/leadService';

export const createLead = async (req: AuthRequest, res: Response) => {
    try {
        if (!req.user) {
            return res.status(401).json({ error: 'Unauthorized' });
        }

        const lead = await leadService.createLead(req.body, req.user.userId);
        res.status(201).json(lead);
    } catch (error: any) {
        console.error('Create lead error:', error);
        res.status(400).json({ error: error.message || 'Failed to create lead' });
    }
};

export const getLeads = async (req: Request, res: Response) => {
    try {
        const leads = await leadService.getAllLeads(req.query);
        res.json(leads);
    } catch (error: any) {
        res.status(500).json({ error: error.message || 'Failed to get leads' });
    }
};

export const getLead = async (req: Request, res: Response) => {
    try {
        const id = parseInt(req.params.id, 10);
        const lead = await leadService.getLeadById(id);
        res.json(lead);
    } catch (error: any) {
        res.status(404).json({ error: error.message || 'Lead not found' });
    }
};

export const updateLead = async (req: AuthRequest, res: Response) => {
    try {
        if (!req.user) {
            return res.status(401).json({ error: 'Unauthorized' });
        }

        const id = parseInt(req.params.id, 10);
        const lead = await leadService.updateLead(id, req.body, req.user.userId);
        res.json(lead);
    } catch (error: any) {
        res.status(400).json({ error: error.message || 'Failed to update lead' });
    }
};
