import jwt from "jsonwebtoken";
import response from "../../response.js";
import models from "../../models/index.js";

export const verifyLoginUser = async (req, res, next) => {
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return response(401, null, "Please log in to your account first!", res);
  }

  const token = authHeader.split(" ")[1];

  try {
    const decoded = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);

    const user = await models.User.findByPk(decoded.ID, {
      attributes: {
        exclude: ["PASSWORD"],
      },
    });

    if (!user) {
      return response(404, null, "User not found!", res);
    }

    req.user = user;

    next();
  } catch (error) {
    if (error.name === "TokenExpiredError") {
      return response(401, null, "Session expired. Please log in again.", res);
    } else if (error.name === "JsonWebTokenError") {
      return response(403, null, "Invalid token!", res);
    } else {
      return response(500, null, "An error occurred on the server!", res);
    }
  }
};

export const adminOnly = (req, res, next) => {
  if (!req.user || req.user.ROLE !== "admin") {
    return response(
      403,
      null,
      "Access denied! You do not have admin access.",
      res
    );
  }
  next();
};

export const teacherOnly = (req, res, next) => {
  if (!req.user || req.user.ROLE !== "teacher") {
    return response(
      403,
      null,
      "Access denied! You do not have teacher access.",
      res
    );
  }
  next();
};

export const adminOrTeacherOnly = (req, res, next) => {
  if (!req.user || (req.user.ROLE !== "admin" && req.user.ROLE !== "teacher")) {
    return response(
      403,
      null,
      "Access denied! You do not have access for this feature.",
      res
    );
  }
  next();
};
