import axios from "axios";
import qs from "qs";

const CLIENT_ID = process.env.ZOOM_CLIENT_ID;
const CLIENT_SECRET = process.env.ZOOM_CLIENT_SECRET;
const ACCOUNT_ID = process.env.ZOOM_ACCOUNT_ID;
// ✅ Add this to your .env: ZOOM_USER_EMAIL=your@zoom-account.com
const ZOOM_USER_EMAIL = process.env.ZOOM_USER_EMAIL || "me";

// ----------------------- GET ACCESS TOKEN -----------------------
export const getZoomAccessToken = async () => {
  const tokenUrl = "https://zoom.us/oauth/token";
  const auth = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64");

  const data = qs.stringify({
    grant_type: "account_credentials",
    account_id: ACCOUNT_ID,
  });

  try {
    const res = await axios.post(tokenUrl, data, {
      headers: {
        Authorization: `Basic ${auth}`,
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });

    return res.data.access_token;
  } catch (err) {
    console.error("❌ Zoom token error:", err.response?.data || err.message);
    throw err;
  }
};

// ----------------------- CREATE MEETING -----------------------
export const createZoomMeeting = async ({
  topic,
  startTime,
  duration,
  email, // ignored — always use ZOOM_USER_EMAIL from env
}) => {
  const token = await getZoomAccessToken();
  const userEmail = ZOOM_USER_EMAIL; // ✅ Always use real email, never "me"

  try {
    const res = await axios.post(
      `https://api.zoom.us/v2/users/${userEmail}/meetings`,
      {
        topic,
        type: 2,
        start_time: startTime,
        duration,
        timezone: "UTC",
        settings: {
          host_video: true,
          participant_video: true,
          join_before_host: false,
          mute_upon_entry: true,
          waiting_room: true,
          approval_type: 0,
          meeting_authentication: false,
        },
      },
      {
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      },
    );

    console.log("✅ Zoom meeting created:", res.data.id);
    return res.data;
  } catch (err) {
    console.error("❌ Zoom meeting error:", err.response?.data || err.message);
    throw err;
  }
};
