import { Response } from 'express';
import { AuthRequest } from '../types/index.js';
import * as emailLogService from '../services/emailLog.service.js';

export async function getEmailLogs(req: AuthRequest, res: Response) {
  try {
    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 50;
    const success = req.query.success !== undefined ? req.query.success === 'true' : undefined;
    const search = req.query.search as string || undefined;
    const context = req.query.context as string || undefined;

    const result = await emailLogService.getEmailLogs({ page, limit, success, search, context });
    res.json({ success: true, ...result });
  } catch (error) {
    console.error('Fehler beim Laden der Email-Logs:', error);
    res.status(500).json({ success: false, error: 'Fehler beim Laden' });
  }
}

export async function getEmailLogStats(req: AuthRequest, res: Response) {
  try {
    const stats = await emailLogService.getEmailLogStats();
    res.json({ success: true, data: stats });
  } catch (error) {
    console.error('Fehler beim Laden der Email-Log-Stats:', error);
    res.status(500).json({ success: false, error: 'Fehler beim Laden' });
  }
}

export async function getEmailLogDetail(req: AuthRequest, res: Response) {
  try {
    const id = parseInt(req.params.id);
    const log = await emailLogService.getEmailLogById(id);
    if (!log) {
      return res.status(404).json({ success: false, error: 'Log-Eintrag nicht gefunden' });
    }
    res.json({ success: true, data: log });
  } catch (error) {
    console.error('Fehler beim Laden des Email-Log-Details:', error);
    res.status(500).json({ success: false, error: 'Fehler beim Laden' });
  }
}
