import { Request, Response, NextFunction } from 'express';
import * as residenceLeadsService from '../services/residenceLeads.service';
import { sendSuccess, sendError } from '../utils/apiResponse';
import { createLeadSchema, updateLeadSchema } from '../validators/residenceLeads.validator';

export const list = async (req: Request, res: Response) => {
  try {
    const leads = await residenceLeadsService.getLeads(parseInt(req.params.projectId as string));
    return sendSuccess(res, 200, 'Liste des leads', leads);
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};

export const create = async (req: Request, res: Response) => {
  try {
    const validated = createLeadSchema.parse(req);
    const result = await residenceLeadsService.createLead(validated.body);
    return sendSuccess(res, 201, 'Lead enregistré', result);
  } catch (error: any) {
    if (error.name === 'ZodError') return sendError(res, 400, 'Données invalides', error.errors);
    return sendError(res, 400, error.message);
  }
};

export const updateStatus = async (req: Request, res: Response) => {
  try {
    const validated = updateLeadSchema.parse(req);
    await residenceLeadsService.updateLeadStatus(parseInt(req.params.id as string), validated.body.status, req.user!.id, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 200, 'Statut du lead mis à jour');
  } catch (error: any) {
    if (error.name === 'ZodError') return sendError(res, 400, 'Données invalides', error.errors);
    return sendError(res, 400, error.message);
  }
};

export const remove = async (req: Request, res: Response) => {
  try {
    await residenceLeadsService.deleteLead(parseInt(req.params.id as string), req.user!.id, req.ip, req.headers['user-agent'] as unknown as string | undefined | undefined);
    return sendSuccess(res, 200, 'Lead supprimé');
  } catch (error: any) {
    return sendError(res, 400, error.message);
  }
};
