// Import the necessary packages and modules
import { AuthUser } from "@/contexts/auth/domain";
import { IServerError } from "@/contexts/common/domain/errors";
import { ExpressController } from "@/contexts/common/infrastructure/express";
import passport from "passport";

export class AuthenticateController extends ExpressController {
  async executeImpl() {
    try {
      return passport.authenticate(
        "local-jwt",
        { session: false },
        (
          err: any,
          user?: AuthUser | false | null,
          info?: object | string | Array<string | undefined>,
          status?: number | Array<number | undefined>
        ) => {
          if (err) {
            return this.next(err);
          }

          if (!user) {
            return this.unauthorizedError("Unauthorized access. No token provided.");
          }

          // If the user is authenticated, attach the user object to the request and move on to the next middleware
          this.req["user"] = user;
          return this.next();
        }
      );
    } catch (e: unknown) {
      return this.fail(e as IServerError);
    }
  }
}
