// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import { app } from "@/firebase";
import { getFirestore, collection, getDocs } from "firebase/firestore";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import axios from "axios";
import { v4 } from "uuid";
import { OrderResponseBody } from "@paypal/paypal-js";
import { getAccessToken } from "@/utils/paypal";

const db = getFirestore(app);

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== "PUT")
    return res.status(404).json({ ok: false, reason: "Method not supported!" });

  if (!req.session.user) return res.status(401).json({ ok: false });

  const accessToken = await getAccessToken();
  if (!accessToken)
    return res.status(401).json({ ok: false, reason: "Authorization failed!" });

  const trackingId = `${req.session.user.id}-${Date.now()}`;

  const url = `${process.env.PAYPAL_ACCESS_TOKEN_URL}/v1/risk/transaction-contexts/${process.env.PAYPAL_MERCHANT_ID}/${trackingId}`;
  const data = {
    additional_data: [
      {
        key: "user_id",
        value: req.session.user.id,
      },
    ],
  };

  const headers = {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  };
  console.log(JSON.stringify({
    url,
    data,
    headers,
  }));
  try {
    const request = await axios.put(url, data, headers);

    return res.status(request.status).json({
      ok: true,
      trackingId,
    });
  } catch (err) {
    console.error(url, err);
    return res
      .status(500)
      .json({ ok: false, reason: "Failed to create tracking ID" });
  }
}
