import * as express from "express";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import { RequestWithUser } from "./user";

export function authRole(
  role: string | string[],
  errorMessage: string = "คุณไม่มีสิทธิในการเข้าถึงทรัพยากรดังกล่าว",
) {
  return (req: RequestWithUser, _res: express.Response, next: express.NextFunction) => {
    if ((Array.isArray(role) && role.includes("*")) || role === "*") return next();

    if (!Array.isArray(role) && !req.user.role.includes(role)) {
      throw new HttpError(HttpStatus.FORBIDDEN, errorMessage);
    }

    if (!req.user.role.some((v) => role.includes(v))) {
      throw new HttpError(HttpStatus.FORBIDDEN, errorMessage);
    }

    return next();
  };
}
