import { Request, Response, NextFunction } from "express"
import jwt from "jsonwebtoken"
import { AppError } from "../core/AppError"

const JWT_SECRET = process.env.JWT_SECRET!

interface JwtPayload {
    sub: string
    type: "admin" | "pos"
    mustChangePassword?: boolean
}

export const protect = (
    req: Request,
    _res: Response,
    next: NextFunction
) => {
    const header = req.headers.authorization

    if (!header?.startsWith("Bearer ")) {
        throw new AppError("Unauthorized", 401)
    }

    const token = header.split(" ")[1]

    try {
        const decoded = jwt.verify(token, JWT_SECRET) as JwtPayload

        req.auth = {
            sub: decoded.sub,
            type: decoded.type,
            mustChangePassword: decoded.mustChangePassword
        }

        next()
    } catch {
        throw new AppError("Invalid token", 401)
    }
}