import { NextFunction, Response } from "express";
import { Request } from "express-serve-static-core";
import { Role } from "@prisma/client";

import { verifyJwt, JwtPayload } from "../lib/jwt";

export interface AuthenticatedRequest extends Request {
  user?: JwtPayload;
}

export const requireAuth = (
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction
) => {
  const auth = req.headers.authorization || "";
  const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
  if (!token) {
    return res.status(401).json({ error: "Missing Authorization token" });
  }
  try {
    const payload = verifyJwt(token);
    req.user = payload;
    return next();
  } catch (e: any) {
    return res.status(401).json({ error: "Invalid token" });
  }
};

export const requireRole = (allowed: Role[]) => {
  return (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
    if (!req.user) {
      return res.status(401).json({ error: "Unauthorized" });
    }
    const userRole = req.user.role as Role | undefined;
    if (!userRole || !allowed.includes(userRole)) {
      return res.status(403).json({ error: "Forbidden" });
    }
    return next();
  };
};
