const express = require('express');
const nodemailer = require('nodemailer');
const config = require('../config');
const router = express.Router();
const createTransporter = () => {
  return nodemailer.createTransport({
    host: config.email.host,
    port: config.email.port,
    auth: {
      user: config.email.user,
      pass: config.email.pass
    }
  });
};
module.exports = (pool, query, authMiddleware) => {
  // Apply authentication middleware to all routes
  router.use(authMiddleware);
  
  // Get all users
  router.get('/', async (req, res, next) => {
    try {
      
      if (!req.user.is_admin) {
        return res.status(403).json({
          error: true,
          message: 'Admin access required'
        });
      }
      
      const result = await query(`
        SELECT 
          id, 
          email, 
          first_name, 
          last_name, 
          is_admin, 
          is_disabled, 
          internal_notes, 
          created_at, 
          last_login
        FROM users
        ORDER BY last_login DESC NULLS LAST
      `);
      
      res.json(result.rows);
    } catch (error) {
      next(error);
    }
  });
  
  // Get single user
  router.get('/:id', async (req, res, next) => {
    try {
      const { id } = req.params;
      
      
      if (!req.user.is_admin) {
        return res.status(403).json({
          error: true,
          message: 'Admin access required'
        });
      }
      
      const result = await query(`
        SELECT 
          id, 
          email, 
          first_name, 
          last_name, 
          is_admin, 
          is_disabled, 
          internal_notes, 
          created_at, 
          last_login
        FROM users 
        WHERE id = $1
      `, [id]);
      
      if (result.rows.length === 0) {
        return res.status(404).json({
          error: true,
          message: 'User not found'
        });
      }
      
      res.json(result.rows[0]);
    } catch (error) {
      next(error);
    }
  });
  
  // Update user (admin can update is_disabled, is_admin and internal_notes)
  router.patch('/:id', async (req, res, next) => {
    try {
      const { id } = req.params;
      const { is_disabled, internal_notes, is_admin} = req.body;
      
      
      if (!req.user.is_admin) {
        return res.status(403).json({
          error: true,
          message: 'Admin access required'
        });
      }
      
      // Check if user exists
      const userCheck = await query('SELECT * FROM users WHERE id = $1', [id]);
      
      if (userCheck.rows.length === 0) {
        return res.status(404).json({
          error: true,
          message: 'User not found'
        });
      }
      
      // Update only allowed fields
      const result = await query(`
        UPDATE users 
        SET 
          is_disabled = $1, 
          internal_notes = $2,
          is_admin = $3
        WHERE id = $4
        RETURNING id, email, first_name, last_name, is_admin, is_disabled, internal_notes
      `, [
        is_disabled !== undefined ? is_disabled : userCheck.rows[0].is_disabled,
        internal_notes !== undefined ? internal_notes : userCheck.rows[0].internal_notes,
        is_admin !== undefined ? is_admin : userCheck.rows[0].is_admin,
        id
      ]);
      
      res.json({
        message: 'User updated successfully',
        user: result.rows[0]
      });
    } catch (error) {
      next(error);
    }
  });

  // Send email to user
  router.post('/send-email', async (req, res, next) => {
    try {
      const { to, name, subject, message } = req.body;
      
      
      if (!req.user.is_admin) {
        return res.status(403).json({
          error: true,
          message: 'Admin access required'
        });
      }
      
      // Validate required fields
      if (!to || !subject || !message) {
        return res.status(400).json({
          error: true,
          message: 'Email, subject, and message are required'
        });
      }
      
      // Create email transporter (using the same transporter from auth.js)
      const transporter = createTransporter();
      
      // Send email
      await transporter.sendMail({
        from: config.email.reply,
        to: to,
        subject: subject,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h2>Message from ${config.site.domain}</h2>
            <p>Dear ${name},</p>
            <div style="padding: 15px; background-color: #f7f7f7; border-radius: 5px;">
              ${message.replace(/\n/g, '<br>')}
            </div>
            <p style="margin-top: 20px; font-size: 12px; color: #666;">
              This email was sent from the admin panel of ${config.site.domain}.
            </p>
          </div>
        `
      });
      
      // Log the email sending (optional)
      await query(
        'INSERT INTO email_logs (recipient, subject, sent_by) VALUES ($1, $2, $3)',
        [to, subject, req.user.id]
      );
      
      res.json({
        success: true,
        message: 'Email sent successfully'
      });
    } catch (error) {
      console.error('Email sending error:', error);
      next(error);
    }
  });
  
  return router;
};