const axios = require('axios');
const { sendSignupEmail } = require('../utils/mailer');
const config = require('../config/config.json');
const { decrypt } = require('../services/encryptionService');

const signupUserRequest = async (req, res) => {
  try {
    const { email, firstName, lastName, password } = req.body;

    if (!email || !firstName || !lastName || !password) {
      return res.status(400).json({ message: 'Email, firstName, lastName, and password are required.' });
    }

    const GHL_API_URL = 'https://rest.gohighlevel.com/v1/users';
    const GHL_API_KEY = decrypt(config.encryptedApiKey); // Decrypt the API key

    const response = await axios.get(GHL_API_URL, {
      headers: {
        Authorization: `Bearer ${GHL_API_KEY}`
      }
    });

    const users = response.data?.users || [];

    // Normalize emails for case-insensitive match
    const requestedEmail = email.trim().toLowerCase();

    const emailExists = users.some(user => {
      const ghlEmail = user?.email?.trim().toLowerCase();
      console.log(`🔍 Comparing: ${requestedEmail} === ${ghlEmail}`);
      return ghlEmail === requestedEmail;
    });

    if (emailExists) {
      return res.status(409).json({ message: 'Email already exists in GoHighLevel.' });
    }

    // Attempt to send signup email (admin + user)
    try {
      const emailResponse = await sendSignupEmail(email, firstName, lastName, password);
      return res.status(200).json({ message: 'Signup request successful.', emailResponse });
    } catch (emailError) {
      // Check if it's a rate limit error (thrown from sendSignupEmail)
      if (emailError.status === 429) {
        return res.status(429).json({ message: emailError.message });
      }

      // Unknown email send failure
      console.error('📧 Email send error:', emailError);
      return res.status(500).json({ message: 'Signup failed while sending email.', error: emailError.message });
    }

  } catch (err) {
    console.error('❌ Signup process error:', err?.response?.data || err.message);
    res.status(500).json({ message: 'Signup failed.', error: err.message });
  }
};


module.exports = { signupUserRequest };