const crypto = require("crypto");

const { createWordPressUser } = require("../utils/wordpress");

const subscription = async (req, res) => {
  try {
    const subscriberData = req.body;
    const email = subscriberData?.billing_email; // Adjust this based on the actual structure of WooCommerce webhook data

    if (!email) {
      res.status(400).send("Email is required");
      return;
    }

    // Generate a random password
    const password = crypto.randomBytes(8).toString("hex");

    // Create a new WordPress user
    const wpResponse = await createWordPressUser(email, email, password);

    if (wpResponse.status === 201) {
      console.log("User created successfully:", wpResponse.data);
      res.status(200).send("User created successfully");
    } else {
      console.error("Error creating user:", wpResponse.data);
      res.status(500).send("Error creating user");
    }
  } catch (error) {
    console.error("Error in subscription handler:", error);
    res.status(500).send("Internal server error");
  }
};

module.exports = {
  subscription,
};
