const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
dotenv.config();

const app = express();
app.use(express.json());
const port = 3000;
app.use(cors());
// --- Helper Function: Send to TikTok ---
async function sendToTikTok(
  event_name,
  event_id,
  user_ip,
  user_agent,
  value,
  currency,
  ttp_cookie
) {
  console.log("Tik tok");
  if (!process.env.TIKTOK_ACCESS_TOKEN) {
    console.log("No TikTok Access Token");
    return;
  }
  try {
    await fetch("https://business-api.tiktok.com/open_api/v1.3/event/track/", {
      method: "POST",
      headers: {
        "Access-Token": process.env.TIKTOK_ACCESS_TOKEN,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        pixel_code: process.env.TIKTOK_PIXEL_ID,
        event: [
          {
            type: event_name, // TikTok uses similar names (InitiateCheckout)
            event_id: event_id,
            timestamp: new Date().toISOString(),
            context: {
              user: {
                ip: user_ip,
                user_agent: user_agent,
              },
              ad: {
                callback: ttp_cookie, // كوكي تيك توك لو موجودة
              },
            },
            properties: {
              currency: currency || "KD",
              value: Number(value) || 0,
            },
          },
        ],
      }),
    });
    console.log("✅ TikTok Request Sent");
  } catch (e) {
    console.error("❌ TikTok Error:", e.message);
  }
}

// --- Helper Function: Send to Snapchat ---
async function sendToSnapchat(
  event_name,
  event_id,
  user_ip,
  user_agent,
  value,
  currency
) {
  if (!process.env.SNAP_ACCESS_TOKEN) return;

  let snapEventName = event_name;
  if (event_name === "InitiateCheckout") snapEventName = "START_CHECKOUT";
  if (event_name === "Contact") snapEventName = "ADD_TO_CART";
  if (event_name === "PageView") snapEventName = "PAGE_VIEW";

  try {
    await fetch("https://tr.snapchat.com/v2/conversion", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.SNAP_ACCESS_TOKEN}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        pixel_id: process.env.SNAP_PIXEL_ID,
        event_type: snapEventName,
        event_conversion_type: "WEB",
        event_id: event_id,
        timestamp: Math.floor(Date.now() / 1000).toString(),
        ipv4: user_ip,
        user_agent: user_agent,
        price: value ? value.toString() : "0",
        currency: currency || "KD",
        integration: "custom_api",
      }),
    });
    console.log("✅ Snap Request Sent");
  } catch (e) {
    console.error("❌ Snap Error:", e.message);
  }
}
// --- Helper Function: Send to Meta ---
async function sendToMeta(event_name, event_id, user_data, custom_data) {
  try {
    const response = await fetch(
      `https://graph.facebook.com/v19.0/${process.env.META_PIXEL_ID}/events?access_token=${process.env.MetaCAPI}`,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          data: [
            {
              event_name: event_name,
              event_time: Math.floor(Date.now() / 1000),
              event_id: event_id,
              user_data: user_data,
              custom_data: custom_data,
              action_source: "website",
            },
          ],
        }),
      }
    );

    const data = await response.json();

    // لو فيسبوك رد بـ Error
    if (data.error) {
      console.error("❌ Meta API Error:", data.error.message);
    } else {
      console.log("✅ Meta Sent Successfully");
    }
  } catch (e) {
    console.error("❌ Meta Network Error:", e.message);
  }
}
// async function sendToSnapchat(
//   event_name,
//   event_id,
//   user_ip,
//   user_agent,
//   value,
//   currency
// ) {
//   if (!process.env.SNAP_ACCESS_TOKEN) return;

//   let snapEventName = event_name;
//   if (event_name === "InitiateCheckout") snapEventName = "START_CHECKOUT";
//   if (event_name === "Contact") snapEventName = "ADD_TO_CART";
//   if (event_name === "PageView") snapEventName = "PAGE_VIEW";

//   const payload = {
//     pixel_id: process.env.SNAP_PIXEL_ID,
//     event_type: snapEventName,
//     event_conversion_type: "WEB",
//     event_id: event_id,
//     timestamp: Math.floor(Date.now() / 1000).toString(),
//     ipv4: user_ip,
//     user_agent: user_agent,
//     price: value ? value.toString() : "0",
//     currency: currency || "KD",
//     integration: "custom_api",
//   };

//   // --- Retry Logic Start ---
//   const maxRetries = 2; // هنحاول مرتين كحد أقصى
//   for (let attempt = 1; attempt <= maxRetries; attempt++) {
//     try {
//       const response = await fetch("https://tr.snapchat.com/v2/conversion", {
//         method: "POST",
//         headers: {
//           Authorization: `Bearer ${process.env.SNAP_ACCESS_TOKEN}`,
//           "Content-Type": "application/json",
//         },
//         body: JSON.stringify(payload),
//       });

//       const data = await response.json();
//       if (data.status === "SUCCESS") {
//         console.log("✅ Snap Sent Successfully");
//         break; // لو نجح، اخرج من اللوب خلاص
//       } else {
//         console.log(`⚠️ Snap Warning (Attempt ${attempt}):`, data);
//       }
//     } catch (e) {
//       console.error(`❌ Snap Error (Attempt ${attempt}): Failed`);
//       if (attempt === maxRetries) {
//         console.error("Giving up on Snap after 2 attempts."); // لو فشل مرتين خلاص
//       } else {
//         // استنى ثانية قبل المحاولة التانية
//         await new Promise((res) => setTimeout(res, 1000));
//       }
//     }
//   }
//   // --- Retry Logic End ---
// }

// app.post("/api/track", async (req, res) => {
//   try {
//     const { event_name, event_id, value, currency, fbp, fbc, ttp } = req.body;

//     if (!event_name) {
//       return res.status(400).json({ error: "Missing event_name" });
//     }

//     const userIp = req.ip || req.connection.remoteAddress;
//     const userAgent = req.headers["user-agent"];

//     let userData = {
//       client_user_agent: userAgent,
//       client_ip_address: userIp,
//       fbp: fbp,
//       fbc: fbc,
//     };

//     console.log(`📡 Sending Event: ${event_name} to ALL platforms...`);

//     // 3. إرسال للكل في نفس الوقت (Parallel Execution)
//     const results = await Promise.allSettled([
//       fetch(
//         `https://graph.facebook.com/v19.0/${process.env.META_PIXEL_ID}/events?access_token=${process.env.MetaCAPI}`,
//         {
//           method: "POST",
//           headers: { "Content-Type": "application/json" },
//           body: JSON.stringify({
//             data: [
//               {
//                 event_name: event_name,
//                 event_time: Math.floor(Date.now() / 1000),
//                 event_id: event_id,
//                 user_data: userData,
//                 custom_data: {
//                   currency: currency || "KD",
//                   value: Number(value) || 0,
//                 },
//                 action_source: "website",
//               },
//             ],
//           }),
//         }
//       ).then(async (res) => {
//         const data = await res.json();
//         console.log("✅ Meta Sent:", data.events_received);
//       }),
//       sendToTikTok(
//         event_name,
//         event_id,
//         userIp,
//         userAgent,
//         value,
//         currency,
//         ttp
//       ),

//       sendToSnapchat(event_name, event_id, userIp, userAgent, value, currency),
//     ]);

//     const metaResult =
//       results[0].status === "fulfilled" ? results[0].value : null;

//     return res.status(200).json({
//       success: true,
//       message: "Requests sent to Meta, TikTok, and Snap",
//       fb_response: metaResult,
//     });
//   } catch (error) {
//     console.error("Global CAPI Error:", error);
//     return res.status(500).json({ success: false, error: error.message });
//   }
// });
app.post("/api/track", (req, res) => {
  try {
    const { event_name, event_id, value, currency, fbp, fbc, ttp } = req.body;

    res
      .status(200)
      .json({ success: true, message: "Tracking started in background" });

    (async () => {
      try {
        console.log(`🚀 Background Task Started: ${event_name}`);

        const userIp = req.ip || req.connection.remoteAddress;
        const userAgent = req.headers["user-agent"];

        // 1. Meta Data Preparation
        const metaUserData = {
          client_user_agent: userAgent,
          client_ip_address: userIp,
          fbp,
          fbc,
        };
        const metaCustomData = {
          currency: currency || "KD",
          value: Number(value) || 0,
        };

        // 2. Run All
        await Promise.allSettled([
          sendToMeta(event_name, event_id, metaUserData, metaCustomData),

          sendToTikTok(
            event_name,
            event_id,
            userIp,
            userAgent,
            value,
            currency,
            ttp
          ),

          sendToSnapchat(
            event_name,
            event_id,
            userIp,
            userAgent,
            value,
            currency
          ),
        ]);

        console.log(`🏁 Background Task Finished: ${event_name}`);
      } catch (bgError) {
        console.error("⚠️ Background Task Error:", bgError.message);
      }
    })();
  } catch (error) {
    console.error("Request Error:", error);
    if (!res.headersSent) res.status(500).json({ success: false });
  }
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
