import { Request, Response, NextFunction } from 'express';
import * as sentEmailsRepo from '../repositories/sentEmails.repository';
import { resendSentEmail } from '../services/notificationSender.service';
import { sendSuccess, sendError } from '../utils/apiResponse';

export const list = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const page = Math.max(1, parseInt(req.query.page as string, 10) || 1);
    const limit = Math.min(100, Math.max(1, parseInt(req.query.limit as string, 10) || 20));
    const search = req.query.search as string | undefined;
    const type = req.query.type as string | undefined;
    const status = req.query.status as string | undefined;

    const { data, total } = await sentEmailsRepo.findAllPaginated(page, limit, search, type, status);
    const stats = await sentEmailsRepo.getStats();

    const totalPages = Math.ceil(total / limit) || 1;

    return sendSuccess(res, 200, 'Liste des e-mails récupérée avec succès', {
      emails: data,
      stats,
    }, {
      page,
      limit,
      total,
      totalPages,
    });
  } catch (error) {
    next(error);
  }
};

export const getOne = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string, 10);
    if (isNaN(id)) {
      return sendError(res, 400, 'Identifiant d\'e-mail invalide');
    }

    const email = await sentEmailsRepo.findById(id);
    if (!email) {
      return sendError(res, 404, 'E-mail introuvable');
    }

    return sendSuccess(res, 200, 'Détail de l\'e-mail récupéré avec succès', email);
  } catch (error) {
    next(error);
  }
};

export const getStats = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const stats = await sentEmailsRepo.getStats();
    return sendSuccess(res, 200, 'Statistiques des e-mails récupérées avec succès', stats);
  } catch (error) {
    next(error);
  }
};

export const resend = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string, 10);
    if (isNaN(id)) {
      return sendError(res, 400, 'Identifiant d\'e-mail invalide');
    }

    const { overrideRecipient } = req.body || {};
    const result = await resendSentEmail(id, overrideRecipient);

    return sendSuccess(res, 200, 'E-mail renvoyé avec succès', result);
  } catch (error: any) {
    return sendError(res, 500, error?.message || 'Erreur lors du renvoi de l\'e-mail');
  }
};

export const remove = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = parseInt(req.params.id as string, 10);
    if (isNaN(id)) {
      return sendError(res, 400, 'Identifiant d\'e-mail invalide');
    }

    const deleted = await sentEmailsRepo.deleteById(id);
    if (!deleted) {
      return sendError(res, 404, 'E-mail introuvable ou déjà supprimé');
    }

    return sendSuccess(res, 200, 'E-mail supprimé de l\'historique avec succès');
  } catch (error) {
    next(error);
  }
};
