const axios = require("axios");
const { query } = require("../../../database/dbpromise");

/**
 * Check if embed addon is enabled
 */
function checkEmbed() {
  return true;
}

/**
 * Exchange authorization code for tokens via Meta OAuth
 * @param {object} params - Exchange parameters
 * @returns {object} - Token exchange result
 */
async function exchangeEmbedToken({
  appId,
  appSecret,
  authCode,
  wabaId,
  phoneNumId,
  businessId,
  registrationPin = "123456",
  redirectUri,
}) {
  try {
    console.log("🔄 Exchanging embed token...");

    // Step 1: Exchange auth code for short-lived token
    const tokenResponse = await axios.get(
      "https://graph.facebook.com/v20.0/oauth/access_token",
      {
        params: {
          client_id: appId,
          client_secret: appSecret,
          redirect_uri: redirectUri || "https://your-domain.com/callback",
          code: authCode,
        },
      }
    );

    const shortLivedToken = tokenResponse.data.access_token;
    console.log("✅ Short-lived token received");

    // Step 2: Exchange short-lived token for long-lived token
    const longLivedResponse = await axios.get(
      "https://graph.facebook.com/v20.0/oauth/access_token",
      {
        params: {
          grant_type: "fb_exchange_token",
          client_id: appId,
          client_secret: appSecret,
          fb_exchange_token: shortLivedToken,
        },
      }
    );

    const longLivedToken = longLivedResponse.data.access_token;
    console.log("✅ Long-lived token received");

    // Step 3: Get user's WABA
    const wabaResponse = await axios.get(
      `https://graph.facebook.com/v20.0/me?fields=whatsapp_business_accounts{id,name}`,
      {
        headers: { Authorization: `Bearer ${longLivedToken}` },
      }
    );

    const wabaData = wabaResponse.data.whatsapp_business_accounts?.data?.[0];
    if (!wabaData) {
      throw new Error("No WhatsApp Business Account found");
    }

    const finalWabaId = wabaId || wabaData.id;
    console.log(`📱 WABA ID: ${finalWabaId}`);

    // Step 4: Get phone numbers for this WABA
    const phonesResponse = await axios.get(
      `https://graph.facebook.com/v20.0/${finalWabaId}/phone_numbers`,
      {
        headers: { Authorization: `Bearer ${longLivedToken}` },
      }
    );

    const phoneData = phonesResponse.data.data?.[0];
    const finalPhoneNumId = phoneNumId || phoneData?.id;

    if (!finalPhoneNumId) {
      throw new Error("No phone number found for this WABA");
    }

    console.log(`📞 Phone Number ID: ${finalPhoneNumId}`);

    // Step 5: Register phone number (if needed)
    try {
      await axios.post(
        `https://graph.facebook.com/v20.0/${finalPhoneNumId}/register`,
        {
          messaging_product: "whatsapp",
          pin: registrationPin,
        },
        {
          headers: { Authorization: `Bearer ${longLivedToken}` },
        }
      );
      console.log("✅ Phone number registered");
    } catch (regError) {
      // Phone might already be registered, ignore error
      console.log("ℹ️ Phone registration skipped:", regError.message);
    }

    // Step 6: Get phone number details
    const phoneDetails = await axios.get(
      `https://graph.facebook.com/v20.0/${finalPhoneNumId}`,
      {
        headers: { Authorization: `Bearer ${longLivedToken}` },
      }
    );

    return {
      success: true,
      message: "Token exchange completed successfully",
      data: {
        access_token: longLivedToken,
        waba_id: finalWabaId,
        waba_name: wabaData.name,
        phone_number_id: finalPhoneNumId,
        phone_number: phoneDetails.data.display_phone_number,
        business_id: businessId,
        quality_rating: phoneDetails.data.quality_rating,
      },
    };
  } catch (error) {
    console.error("❌ Error exchanging embed token:", error.response?.data || error.message);
    return {
      success: false,
      message: error.response?.data?.error?.message || error.message,
    };
  }
}

/**
 * Generate embed webhook URL
 */
async function genEmbedWebhook(params = {}) {
  try {
    const baseUrl = process.env.BACKURI || process.env.FRONTENDURI || "https://your-domain.com";
    const webhookUrl = `${baseUrl}/api/inbox/embed/webhook`;

    return {
      success: true,
      webhook_url: webhookUrl,
    };
  } catch (error) {
    console.error("Error generating embed webhook:", error);
    return {
      success: false,
      message: error.message,
    };
  }
}

/**
 * Register phone number with Meta
 */
async function registerPhoneNumber({ token, phoneNumId, pin = "123456" }) {
  try {
    const response = await axios.post(
      `https://graph.facebook.com/v20.0/${phoneNumId}/register`,
      {
        messaging_product: "whatsapp",
        pin: pin,
      },
      {
        headers: { Authorization: `Bearer ${token}` },
      }
    );

    return {
      success: true,
      message: "Phone number registered successfully",
      data: response.data,
    };
  } catch (error) {
    console.error("Error registering phone number:", error.response?.data || error.message);
    return {
      success: false,
      message: error.response?.data?.error?.message || error.message,
    };
  }
}

/**
 * Get phone number status
 */
async function getPhoneNumberStatus({ token, phoneNumId }) {
  try {
    const response = await axios.get(
      `https://graph.facebook.com/v20.0/${phoneNumId}`,
      {
        headers: { Authorization: `Bearer ${token}` },
      }
    );

    return {
      success: true,
      data: response.data,
    };
  } catch (error) {
    console.error("Error getting phone status:", error.response?.data || error.message);
    return {
      success: false,
      message: error.response?.data?.error?.message || error.message,
    };
  }
}

/**
 * Subscribe to webhook for a WABA
 */
async function subscribeWebhook({ token, wabaId }) {
  try {
    const response = await axios.post(
      `https://graph.facebook.com/v20.0/${wabaId}/subscribed_apps`,
      {},
      {
        headers: { Authorization: `Bearer ${token}` },
      }
    );

    return {
      success: true,
      message: "Webhook subscribed successfully",
      data: response.data,
    };
  } catch (error) {
    console.error("Error subscribing webhook:", error.response?.data || error.message);
    return {
      success: false,
      message: error.response?.data?.error?.message || error.message,
    };
  }
}

/**
 * Get WABA (WhatsApp Business Account) details
 */
async function getWABADetails({ token, wabaId }) {
  try {
    const response = await axios.get(
      `https://graph.facebook.com/v20.0/${wabaId}`,
      {
        headers: { Authorization: `Bearer ${token}` },
      }
    );

    return {
      success: true,
      data: response.data,
    };
  } catch (error) {
    console.error("Error getting WABA details:", error.response?.data || error.message);
    return {
      success: false,
      message: error.response?.data?.error?.message || error.message,
    };
  }
}

module.exports = {
  checkEmbed,
  exchangeEmbedToken,
  genEmbedWebhook,
  registerPhoneNumber,
  getPhoneNumberStatus,
  subscribeWebhook,
  getWABADetails,
};
