const express = require('express');
const { Feedback, User } = require('../models');
const { authenticateToken } = require('../middleware/auth');
const { validateFeedback, sanitizeInput } = require('../middleware/validation');
const logger = require('../utils/logger');
const emailServices = require('../services/email');
const router = express.Router();

// Submit new feedback
router.post('/', authenticateToken, sanitizeInput, validateFeedback, async (req, res, next) => {
  try {
    const { feedbackText, url } = req.body;

    // Capture user agent from request headers
    const userAgent = req.headers['user-agent'];

    const feedback = await Feedback.create({
      userId: req.user.id,
      feedbackText,
      url: url || null,
      userAgent: userAgent || null
    });

    const reqLogger = logger.withRequestId(req.id);
    reqLogger.info("Feedback submitted", {
      userId: req.user.id,
      feedbackId: feedback.id
    });

    // Send confirmation email to user
    try {
      await emailServices.feedback.sendFeedbackConfirmation(req.user, feedback);
    } catch (emailError) {
      reqLogger.error("Failed to send feedback confirmation email", {
        error: emailError.message,
        stack: emailError.stack,
        userId: req.user.id,
        feedbackId: feedback.id
      });
      // Don't fail the request if email fails
    }

    // Send notification email to admin
    try {
      await emailServices.feedback.sendFeedbackNotificationToAdmin(req.user, feedback);
    } catch (emailError) {
      reqLogger.error("Failed to send feedback notification to admin", {
        error: emailError.message,
        stack: emailError.stack,
        userId: req.user.id,
        feedbackId: feedback.id
      });
      // Don't fail the request if email fails
    }

    res.status(201).json(feedback);
  } catch (error) {
    const reqLogger = logger.withRequestId(req.id);
    reqLogger.error("Feedback submission failed", {
      error: error.message,
      stack: error.stack,
      userId: req.user.id
    });
    next(error);
  }
});

module.exports = router;
