const express = require('express');
const router = express.Router();

module.exports = (pool, query, authMiddleware) => {
  // Apply authentication middleware to all routes
  router.use(authMiddleware);
  
  // Get all pending comments (admin)
  router.get('/pending', async (req, res, next) => {
    try {
      
      if (!req.user.is_admin) {
        return res.status(403).json({
          error: true,
          message: 'Admin access required'
        });
      }
      
      // Get all pending comments with related data
      const result = await query(`
        SELECT 
          c.id, c.content, c.created_at, 
          c.parent_id, c.post_id, c.user_id,
          u.first_name, u.last_name, u.email,
          b.title as post_title, b.slug as post_slug
        FROM blog_comments c
        JOIN users u ON c.user_id = u.id
        JOIN blog_posts b ON c.post_id = b.id
        WHERE c.is_approved = false
        ORDER BY c.created_at DESC
      `);
      
      res.json(result.rows);
    } catch (error) {
      next(error);
    }
  });
  
  // Get all comments for a post (admin)
  router.get('/posts/:postId', async (req, res, next) => {
    try {
      const { postId } = req.params;
      
      
      if (!req.user.is_admin) {
        return res.status(403).json({
          error: true,
          message: 'Admin access required'
        });
      }
      
      // Check if post exists
      const postCheck = await query(
        'SELECT id, title FROM blog_posts WHERE id = $1',
        [postId]
      );
      
      if (postCheck.rows.length === 0) {
        return res.status(404).json({
          error: true,
          message: 'Blog post not found'
        });
      }
      
      const post = postCheck.rows[0];
      
      // Get all comments for the post
      const commentsQuery = `
        SELECT 
          c.id, c.content, c.created_at,
          c.parent_id, c.is_approved,
          u.id as user_id, u.first_name, u.last_name, u.email
        FROM blog_comments c
        JOIN users u ON c.user_id = u.id
        WHERE c.post_id = $1
        ORDER BY c.created_at DESC
      `;
      
      const commentsResult = await query(commentsQuery, [postId]);
      
      // Organize comments into threads
      const commentThreads = [];
      const commentMap = {};
      
      // First, create a map of all comments
      commentsResult.rows.forEach(comment => {
        commentMap[comment.id] = {
          ...comment,
          replies: []
        };
      });
      
      // Then, organize into threads
      commentsResult.rows.forEach(comment => {
        if (comment.parent_id) {
          // This is a reply
          if (commentMap[comment.parent_id]) {
            commentMap[comment.parent_id].replies.push(commentMap[comment.id]);
          }
        } else {
          // This is a top-level comment
          commentThreads.push(commentMap[comment.id]);
        }
      });
      
      res.json({
        post: {
          id: post.id,
          title: post.title
        },
        comments: commentThreads
      });
    } catch (error) {
      next(error);
    }
  });
  
  // Approve a comment
  router.post('/:commentId/approve', async (req, res, next) => {
    try {
      const { commentId } = req.params;
      
      
      if (!req.user.is_admin) {
        return res.status(403).json({
          error: true,
          message: 'Admin access required'
        });
      }
      
      // Check if comment exists
      const commentCheck = await query(
        'SELECT id, is_approved FROM blog_comments WHERE id = $1',
        [commentId]
      );
      
      if (commentCheck.rows.length === 0) {
        return res.status(404).json({
          error: true,
          message: 'Comment not found'
        });
      }
      
      // Check if comment is already approved
      if (commentCheck.rows[0].is_approved) {
        return res.status(400).json({
          error: true,
          message: 'Comment is already approved'
        });
      }
      
      // Approve comment
      const result = await query(
        'UPDATE blog_comments SET is_approved = true WHERE id = $1 RETURNING *',
        [commentId]
      );
      
      res.json({
        message: 'Comment approved successfully',
        comment: result.rows[0]
      });
    } catch (error) {
      next(error);
    }
  });
  
  // Delete a comment
  router.delete('/:commentId', async (req, res, next) => {
    try {
      const { commentId } = req.params;
      
      
      if (!req.user.is_admin) {
        return res.status(403).json({
          error: true,
          message: 'Admin access required'
        });
      }
      
      // Check if comment exists
      const commentCheck = await query(
        'SELECT id FROM blog_comments WHERE id = $1',
        [commentId]
      );
      
      if (commentCheck.rows.length === 0) {
        return res.status(404).json({
          error: true,
          message: 'Comment not found'
        });
      }
      
      // Delete comment - cascade will handle child comments
      await query(
        'DELETE FROM blog_comments WHERE id = $1',
        [commentId]
      );
      
      res.json({
        message: 'Comment deleted successfully'
      });
    } catch (error) {
      next(error);
    }
  });
  
  return router;
};