import axios from 'axios';
import jwt from 'jsonwebtoken';
import common from '../src/helpers/common';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '../pages/api/auth/[...nextauth]';
import { red } from '@mui/material/colors';

const axiosServer = async (context) => {
  let headers = {
    'Content-Type': 'application/json',
  };

  const session = await getServerSession(context.req || req, context.res || res, authOptions);
  context.req.session = session;

  if (session) {
    const secret = process.env.NEXTAUTH_SECRET;
    if (!secret) {
      throw new Error('NEXTAUTH_SECRET is not set');
    }

    const token = jwt.sign({ ...session }, secret, { expiresIn: '1h' });
    headers['Authorization'] = `Bearer ${token}`;
    //headers['X-From-Server'] = token; // Note: Using the entire token as a header value might not be intended

    return axios.create({
      baseURL: common.getBaseUrl("", context.req || req),
      withCredentials: true,
      headers: headers,
    });
  }
  else {
    //redirect to next-auth login page
    //context.res.writeHead(302, { Location: encodeURIComponent('/api/auth/signin') });

    context.res.end();
    return { props: {} };
  }
};

export default axiosServer;
