import jwt from "jsonwebtoken";
import { env } from "../shared/env.js";
import { httpError } from "../shared/errors.js";
import { User } from "../modules/users/user.model.js";

export async function requireAuth(req, _res, next) {
  try {
    const header = req.headers.authorization || "";
    const [, bearerToken] = header.split(" ");
    const cookieToken = req.cookies?.token;
    const token = bearerToken || cookieToken;

    if (!token) return next(httpError(401, "Missing bearer token"));

    const payload = jwt.verify(token, env.JWT_SECRET);
    const user = await User.findById(payload.sub).lean();
    if (!user) return next(httpError(401, "Invalid token"));
    if (user.status !== "active") return next(httpError(403, "User disabled"));

    req.user = user;
    return next();
  } catch {
    return next(httpError(401, "Invalid token"));
  }
}

export function requireRole(...roles) {
  return (req, _res, next) => {
    if (!req.user) return next(httpError(401, "Unauthorized"));
    if (!roles.includes(req.user.role))
      return next(httpError(403, "Forbidden"));
    return next();
  };
}

export function signToken(userId) {
  return jwt.sign({ sub: userId }, env.JWT_SECRET, {
    expiresIn: env.JWT_EXPIRES_IN,
  });
}
