import axios from "axios";
import { NextApiRequest, NextApiResponse } from "next";
import NextAuth from "next-auth/next";
import GoogleProvider from "next-auth/providers/google";
import FacebookProvider from "next-auth/providers/facebook";

export default async function auth(req: NextApiRequest, res: NextApiResponse) {
  return await NextAuth(req, res, {
    providers: [
      GoogleProvider({
        clientId: process.env.NEXTAUTH_GOOGLE_CLIENT_ID || "",
        clientSecret: process.env.NEXTAUTH_GOOGLE_SECRET || "",
        authorization:
          "https://accounts.google.com/o/oauth2/auth?prompt=select_account",
      }),
      FacebookProvider({
        idToken: true,
        clientId: process.env.NEXTAUTH_FACEBOOK_APP_ID || "",
        clientSecret: process.env.NEXTAUTH_FACEBOOK_APP_CLIENT_SECRET || "",
        authorization: {
          url: "https://www.facebook.com/v11.0/dialog/oauth",
          params: {
            client_id: process.env.NEXTAUTH_FACEBOOK_APP_ID,
            scope: "openid email",
            response_type: "code",
          },
        },
        token: {
          url: "https://graph.facebook.com/oauth/access_token",
          async request(context) {
            const url =
              `https://graph.facebook.com/oauth/access_token` +
              `?code=${context.params.code}` +
              `&client_id=${context.provider.clientId}` +
              `&redirect_uri=${context.provider.callbackUrl}` +
              `&client_secret=${context.provider.clientSecret}`;
            const response = await fetch(url);
            const tokens = await response.json();
            return { tokens };
          },
        },
      }),
    ],
    secret: process.env.NEXTAUTH_SECRET || "",
    callbacks: {
      async signIn({ user, account, profile }: any) {

        // const cookies = parse(req.headers.cookie || '');
        // const _refCode = cookies.referralCode;

        if (account?.provider === "google") {
          const userAgent = req ? req.headers['user-agent'] || 'unknown' : navigator.userAgent;
 
          try {
            let data = {
              firstName: profile.given_name,
              lastName: profile.family_name,
              email: profile.email,
              phoneCode:'+234',
              socialId: user.id,
              provider: "google",
              // referralCode:_refCode
            }
            const response = await axios.post(`https://api.jazzagain.com/public/index.php/api/auth/socialLogin`, data)
            console.log("RESPONSE ===> ", response.data)
            res.setHeader(
              'Set-Cookie',
              `jazz_token=${response.data.access_token}; Path=/; Max-Age=2592000`
            );
              fetch('https://api.ipify.org?format=json')
              .then(res => res.json())
              .then((data:any) => {
                const activityData = {
                  userId: response.data.user._id,
                  source:'website',
                  page:'/',
                  action:{
                    userLogin:'google login completed'
                  },
                  ipAddress:data?.ip,
                  userAgent:userAgent
                }
                axios.post('https://api.jazzagain.com/public/index.php/api/userActivity',activityData)
                .then((res:any)=>{
                }).catch(error =>console.error('Error saving activity:', error))
              })
              .catch(error => console.error('Error fetching IP:', error));
      
          } catch (e) {
            throw { code: 0, message: "Something went wrong !" };
          }
        }else{
          try {
            let data = {
              firstName: profile.name,
              email: profile.email,
              phoneCode:'+234',
              socialId: user.id,
              provider: "facebook",
              // referralCode:_refCode
            }
            const response = await axios.post(`https://api.jazzagain.com/public/index.php/api/auth/socialLogin`, data)
            // console.log("RESPONSE ===> ", response.data)
            const userAgent = req ? req.headers['user-agent'] || 'unknown' : navigator.userAgent;
            res.setHeader(
              'Set-Cookie',
              `jazz_token=${response.data.access_token}; Path=/; Max-Age=2592000`
            );
            fetch('https://api.ipify.org?format=json')
            .then(res => res.json())
            .then((data:any) => {
              const activityData = {
                userId: response.data.user._id,
                source:'website',
                page:'/',
                action:{
                  userLogin:'facebook login completed'
                },
                ipAddress:data.ip,
                userAgent:userAgent
              }
              axios.post('https://api.jazzagain.com/public/index.php/api/userActivity',activityData)
              .then((res:any)=>{
              }).catch(error =>console.error('Error saving activity:', error))
            })
            .catch(error => console.error('Error fetching IP:', error));
          } catch (e) {
            throw { code: 0, message: "Something went wrong !" };
          }
        }
        return true;
      },
      async redirect({ url, baseUrl }) {
        return url.startsWith(baseUrl) ? url : baseUrl;
      },
    },
    pages: {
      signIn: "/auth/login",
    },
  });
}
