import { Router } from 'express';
import { z } from 'zod';
import { UserRole } from '@prisma/client';
import { errorReportRateLimit } from '../../middleware/rate-limit';
import { getAdminEmailsByRole } from '../../services/notification.helper';
import { emailService } from '../../services/email.service';
import { logger } from '../../utils/logger';

const errorReportSchema = z.object({
  url: z.string().min(1).max(2000),
  message: z.string().max(500).optional(),
  userAgent: z.string().max(500).optional(),
});

export const errorReportRouter = Router();

errorReportRouter.post('/', errorReportRateLimit, async (req, res) => {
  try {
    const parsed = errorReportSchema.safeParse(req.body);
    if (!parsed.success) {
      res.status(400).json({ error: { message: 'Invalid input', code: 'VALIDATION_ERROR' } });
      return;
    }

    const { url, message: userMessage, userAgent } = parsed.data;

    const adminEmails = await getAdminEmailsByRole([UserRole.SUPER_ADMIN]);
    if (adminEmails.length === 0) {
      logger.warn('No super admin emails found for 404 error report');
      res.json({ success: true });
      return;
    }

    const timestamp = new Date().toISOString();
    const ip = req.ip || req.socket.remoteAddress || 'unknown';

    const html = `
      <h2>404 Error Report</h2>
      <table style="border-collapse:collapse; font-family:sans-serif;">
        <tr><td style="padding:4px 12px 4px 0; font-weight:bold;">URL:</td><td>${escapeHtml(url)}</td></tr>
        ${userMessage ? `<tr><td style="padding:4px 12px 4px 0; font-weight:bold;">Message:</td><td>${escapeHtml(userMessage)}</td></tr>` : ''}
        <tr><td style="padding:4px 12px 4px 0; font-weight:bold;">IP:</td><td>${escapeHtml(ip)}</td></tr>
        ${userAgent ? `<tr><td style="padding:4px 12px 4px 0; font-weight:bold;">User Agent:</td><td>${escapeHtml(userAgent)}</td></tr>` : ''}
        <tr><td style="padding:4px 12px 4px 0; font-weight:bold;">Timestamp:</td><td>${timestamp}</td></tr>
      </table>
    `;

    const text = [
      '404 Error Report',
      `URL: ${url}`,
      userMessage ? `Message: ${userMessage}` : '',
      `IP: ${ip}`,
      userAgent ? `User Agent: ${userAgent}` : '',
      `Timestamp: ${timestamp}`,
    ].filter(Boolean).join('\n');

    // Send to each admin (fire-and-forget per recipient)
    for (const email of adminEmails) {
      emailService.sendEmail({
        to: email,
        subject: `[404 Report] Page not found: ${url.slice(0, 100)}`,
        html,
        text,
      }).catch((err) => {
        logger.error('Failed to send 404 report email', { to: email, error: err instanceof Error ? err.message : String(err) });
      });
    }

    res.json({ success: true });
  } catch (err) {
    logger.error('Error report submission failed', { error: err instanceof Error ? err.message : String(err) });
    res.status(500).json({ error: { message: 'Internal server error', code: 'INTERNAL_ERROR' } });
  }
});

function escapeHtml(str: string): string {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}
