import UserList from "../Models/Users/Users";
import { ISession } from "../Models/Session.model";
import { NextFunction, Request, Response } from "express";
import { ApiValidationError } from "../Models/Server.Error.model";

export async function authenticateMiddleware(
    request: Request,
    response: Response,
    next: NextFunction
): Promise<void | Response | ApiValidationError> {
    const token = request.headers.authorization;

    if (token === "" || token === undefined) {
        return response
            .status(501)
            .json(new ApiValidationError(501, "No autorizado"));
    }

    try {
        const session: ISession = await UserList.loginByToken({ token });

        const { sessionUser } = request.body;

        if (sessionUser) {
            if (sessionUser !== session.userId) {
                return response
                    .status(501)
                    .json(
                        new ApiValidationError(
                            501,
                            "Credenciales de acceso no coinciden con el usuario. No autorizado"
                        )
                    );
            }
        }

        next();
    } catch (error) {
        return response
            .status(501)
            .json(new ApiValidationError(501, "Credenciales de acceso no validas. No autorizado"));
    }
}
