// server.js
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import dataRoutes from "./routes/dataRoutes.js";
import inventoryRoutes from "./routes/inventoryRoutes.js";
import cookieParser from 'cookie-parser';

dotenv.config();

const app = express();

app.use(cors());
app.use(express.json());
app.use(cookieParser());

app.use("/api/data", dataRoutes);
app.use("/api/inventory", inventoryRoutes);

/*
    the below code needs to be encapsulated somehow.  It requires a manual flow, including QUICKLY copy/pasting the code query string from the result of localhost:300/auth/ebay (below)
    
    Here are the steps:
    1.  Go to localhost:3000/auth/ebay and copy/paste query string from code
    2.  Quickly go to the editor and paste that code into the const code= at /auth/ebay/callback
    3.  Go to localhost:3000/auth/ebay/callback and tokens will be in console - this is an 18 month deal, so we should tuck this code away

    That is not really a callback... that was my intention, but it did not work out that way.  That is simply an explicit API call to grab a user/refresh token from the manual process above

    Next ToDos:
    1. change the name of fetchEbayToken to fetchEbayReadToken
    2.  Add a fetchEbayUserToken endpoint and figure how to cycle user tokens every 2 hours with refresh token
    3. Add refresh token to .env and figure out how to safely store user tokens serverside (cookie?  knowledge gap here)
*/
app.get('/auth/ebay', async (req, res) => {
    // the below URL is hardcoded because it's static in the eBay dev dashboard
    const authUrl = `https://auth.ebay.com/oauth2/authorize?client_id=TylerPul-ebayimpo-PRD-a983027cf-9b6b8bba&response_type=code&redirect_uri=Tyler_Pulse-TylerPul-ebayim-ledkmyo&scope=https://api.ebay.com/oauth/api_scope https://api.ebay.com/oauth/api_scope/sell.marketing.readonly https://api.ebay.com/oauth/api_scope/sell.marketing https://api.ebay.com/oauth/api_scope/sell.inventory.readonly https://api.ebay.com/oauth/api_scope/sell.inventory https://api.ebay.com/oauth/api_scope/sell.account.readonly https://api.ebay.com/oauth/api_scope/sell.account https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly https://api.ebay.com/oauth/api_scope/sell.fulfillment https://api.ebay.com/oauth/api_scope/sell.analytics.readonly https://api.ebay.com/oauth/api_scope/sell.finances https://api.ebay.com/oauth/api_scope/sell.payment.dispute https://api.ebay.com/oauth/api_scope/commerce.identity.readonly https://api.ebay.com/oauth/api_scope/sell.reputation https://api.ebay.com/oauth/api_scope/sell.reputation.readonly https://api.ebay.com/oauth/api_scope/commerce.notification.subscription https://api.ebay.com/oauth/api_scope/commerce.notification.subscription.readonly https://api.ebay.com/oauth/api_scope/sell.stores https://api.ebay.com/oauth/api_scope/sell.stores.readonly`;
    res.redirect(authUrl); // Redirect the user to eBay's sign-in page
  });
  
  // Step 2: Handle the redirect from eBay
  app.get('/auth/ebay/callback', async (req, res) => {
    // this code comes from a query string at localhost:3000/auth/ebay when we redirect
    const code = 'v%5E1.1%23i%5E1%23p%5E3%23f%5E0%23r%5E1%23I%5E3%23t%5EUl41Xzc6NUE2ODc0NkU5Q0Q4N0QxQjhENTVCNzAxQTAwMEM2MzlfMF8xI0VeMjYw'
    try {
      // Step 3: Exchange the authorization code for access and refresh tokens
      const tokenResponse = await fetch('https://api.ebay.com/identity/v1/oauth2/token', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': `Basic ${Buffer.from(`${process.env.EBAY_CLIENT_ID}:${process.env.EBAY_CLIENT_SECRET}`).toString('base64')}`
        },
        // we use Tyler_Pulse-TylerPul-ebayim-ledkmyo and not the initial redirect URL
        body: `grant_type=authorization_code&code=${code}&redirect_uri=Tyler_Pulse-TylerPul-ebayim-ledkmyo`
      });
  
      if (!tokenResponse.ok) {
        throw new Error('Failed to exchange authorization code for tokens');
      }
  
      const tokenData = await tokenResponse.json();
      console.log('Access Token:', tokenData.access_token);
      console.log('Refresh Token:', tokenData.refresh_token);
  
      res.send('Authentication successful! Tokens acquired.'); // For demonstration purposes; you might want to redirect the user or show a different message
    } catch (error) {
      console.error('Error during token exchange:', error);
      res.status(500).send('Internal Server Error');
    }
  });
  
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
