// filepath: c:\Users\amaizy\Desktop\cvgen\controllers\linkedin.js

const axios = require("axios");
const querystring = require("querystring");

const clientId = "780w7gsy8eysmj";
const clientSecret = "WPL_AP1.w6OTTkAndAdT3PYF.UZEcwQ==";
const redirectUri = "http://localhost:3000/api/auth/linkedin/callback";
const scope = "r_liteprofile r_emailaddress";

let accessToken = "";

const authenticateUser = (req, res) => {
  const authUrl = `https://www.linkedin.com/oauth/v2/authorization?${querystring.stringify(
    {
      response_type: "code",
      client_id: clientId,
      redirect_uri: redirectUri,
      scope: scope,
    }
  )}`;
  res.redirect(authUrl);
};

const callback = async (req, res) => {
  const { code } = req.query;

  try {
    const tokenResponse = await axios.post(
      "https://www.linkedin.com/oauth/v2/accessToken",
      querystring.stringify({
        grant_type: "authorization_code",
        code: code,
        redirect_uri: redirectUri,
        client_id: clientId,
        client_secret: clientSecret,
      })
    );

    accessToken = tokenResponse.data.access_token;
    res.send(
      "Authentication successful! You can now retrieve your profile information."
    );
  } catch (error) {
    res.status(500).send("Error retrieving access token.");
  }
};

const getUserProfile = async (req, res) => {
  try {
    const profileResponse = await axios.get("https://api.linkedin.com/v2/me", {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    res.json(profileResponse.data);
  } catch (error) {
    res.status(500).send("Error retrieving user profile.");
  }
};

module.exports = {
  authenticateUser,
  callback,
  getUserProfile,
};
