import NextAuth from "next-auth";
import axios from "axios";
import Credentials from "next-auth/providers/credentials";
import {SignJWT} from "jose";

const SMSOTPProvider = Credentials({
  id: "sms-otp",
  name: "SMS OTP",
  credentials: {
    phoneNumber: { label: "Phone Number", type: "tel" },
    otp: { label: "OTP", type: "text" },
  },
  authorize: async ({ phoneNumber, otp }: any) => {
    try {
      if (!otp) {
        // If OTP is not provided, generate a new one
        const tokenGenerated = await generateToken(phoneNumber);
        if (!tokenGenerated) {
          throw new Error("Failed to generate OTP");
        }
        return null; // Return null to indicate that OTP has been sent
      }

      // Verify OTP
      const isValid = await verifyOTP(phoneNumber, otp);
      if (isValid) {
        // Return a user object if OTP is valid
        const response = await axios.post(
          "http://192.168.31.187:8000/api/login/verify_otp",
          { mobile_no: phoneNumber, otp: otp },
          {
            headers: {
              "Content-Type": "application/json",
              accept: "application/json",
            },
          },
        );
        const authToken = response.data.auth_token;
        return { id: phoneNumber, phoneNumber, authToken };
      }
      return null;
    } catch (error) {
      console.error("Error in authorize function:", error);
      throw error;
    }
  },
});

export const { handlers, auth } = NextAuth({
  providers: [SMSOTPProvider],
  debug: true,
  jwt: {
    async encode({ token, user, account, isNewUser, session }:any) {
      if (user) {
        token.authToken = user.authToken;
      }
      const secret = new TextEncoder().encode(process.env.NEXT_PUBLIC_JWT_SECRET!);
      const jwt = await new SignJWT(token)
          .setProtectedHeader({ alg: "HS256" })
          .sign(secret);
      return jwt;
    },
  callbacks: {
    async jwt(token, user, account, profile, isNewUser) {
      if (user) {
        token.authToken = user.authToken;
      }
      return token;
    },
    async session(session, token) {
      session.user.authToken = token.authToken;
      return session;
    },
  },
});

async function generateToken(phoneNumber: string): Promise<boolean> {
  try {
    const response = await axios.post(
      "http://192.168.31.187:8000/api/login/generate_token",
      { mobile_no: phoneNumber },
      {
        headers: {
          "Content-Type": "application/json",
          accept: "application/json",
        },
      },
    );
    return response.status === 200;
  } catch (error) {
    console.error("Error generating OTP:", error);
    return false;
  }
}

async function verifyOTP(phoneNumber: string, otp: string): Promise<boolean> {
  try {
    const response = await axios.post(
      "http://192.168.31.187:8000/api/login/verify_otp",
      { mobile_no: phoneNumber, otp: otp },
      {
        headers: {
          "Content-Type": "application/json",
          accept: "application/json",
        },
      },
    );
    return response.status === 200;
  } catch (error) {
    console.error("Error verifying OTP:", error);
    return false;
  }
}
make this auth.ts file of the authjs fully typescript friendly without any ts errord