import Env from "@ioc:Adonis/Core/Env";
import jwt from "jsonwebtoken";
import type { HttpContextContract } from "@ioc:Adonis/Core/HttpContext";
// import { loggerAPI } from "App/utils/logger";
// import jwtDecode from "jwt-decode";

export default class CheckToken {
  public async handle(
    { request, response }: HttpContextContract,
    next: () => Promise<void>
  ) { 
    // code for middleware goes here. ABOVE THE NEXT CALL
    try {
      // const user = jwtDecode(request.headers().authorization);
      console.log("first", await jwt.verify(
        request.headers().authorization?.replace(/"/g, ""),
        Env.get("JWT_KEY")))
      let abc = await jwt.verify(
        request.headers().authorization?.replace(/"/g, ""),
        Env.get("JWT_KEY"),
        async function (err, decoded) {
          if (err) {
            console.log(err)
            response.status(203).send("Token invalid");
            // loggerAPI(
            //   request,
            //   response,
            //   user,
            //   "Middleware CheckToken - " + request.url()
            // );
          } else {
            await next();
          }
        }
      );
      console.log(abc)
    } catch (error) {
      console.log("sdfs", error)
      response.status(203).send("Token invalid");
      // loggerAPI(
      //   request,
      //   response,
      //   request.headers().email,
      //   "Middleware CheckToken - " + request.url()
      // );
    }
  }
}
