import { NextFunction, Request, Response } from "express";
import { EStatuses } from "../enum/EStatuses";
import IResponse from "../interfaces/IResponse";
import jwt from 'jsonwebtoken'
import IModifiedRequest from "../interfaces/IModifiedRequest";


export const auth = (expressReq:Request, res: Response, next: NextFunction) => {
    try {
        const req = expressReq as IModifiedRequest        
        if (req.method === 'OPTIONS'){
            next()
        }
        const token = req.header('Authorization')?.replace('Bearer ', '');
        if (!token){
            throw new Error('Token not provided')
        } 
        const verifiedData = jwt.verify(token, process.env.SECRET_KEY as string);
        req.verifiedData = verifiedData
        next()
    } catch(err: unknown) {
        const error = err as Error
        const response: IResponse<null> = {
            status: EStatuses.FAILURE,
            result: null,
            message: error.message
        }
        res.status(418).send(response)
    }
}