const jwt = require("jsonwebtoken");
const {
  users,
  project_topics,
  subscriptions,
  departments,
  institutes,
  study_modes,
} = require("../../models");

const renderErrorResponse = (res) => {
  return res.redirect("/student-login");
  return res.render("login/student.ejs", {
    error: {
      statusCode: "401",
      success: false,
      message: "Error",
      error: "Login to access the student dashboard",
    },
    success: {
      statusCode: "200",
      success: false,
      message: undefined,
    },
  });
};

const auth = async (req, res, next) => {
  try {
    const sessionToken = req?.session?.data?.token;
    if (!sessionToken) {
      return renderErrorResponse(res);
    }

    let decoded;
    try {
      decoded = jwt.verify(sessionToken, process.env.JWT_pa);
    } catch (err) {
      if (err instanceof jwt.JsonWebTokenError) {
        return renderErrorResponse(res);
      }
      throw err;
    }

    let authUser = await users.findOne({
      where: {
        username: decoded.username,
      },
      attributes: [
        "id",
        "password",
        "username",
        "second_role",
        "payment_status",
        "first_login",
        "middlename",
        "firstname",
        "lastname",
        "session_id",
        "department_id",
      ],
      include: [
        {
          model: study_modes,
          attributes: ["name"],
        },
        {
          model: departments,
          attributes: ["id", "name"],
          include: [
            {
              model: institutes,
              attributes: ["name"],
            },
          ],
        },
      ],
    });

    if (!authUser) {
      return renderErrorResponse(res);
    }
    authUser = JSON.parse(JSON.stringify(authUser));
    const topics = await project_topics.findOne({
      where: { student_user_id: authUser.id, active: true, is_approved: true },
    });
    authUser.topics = topics;
    const FinalYearProject = await subscriptions.findOne({
      attributes: ["active"],
      where: {
        pakage_id: 1,
        user_id: authUser.id,
      },
    });

    const SiwesTechnicalReport = await subscriptions.findOne({
      attributes: ["active"],
      where: {
        active: 1,
        pakage_id: 2,
        user_id: authUser.id,
      },
    });

    const SeminarReport = await subscriptions.findOne({
      attributes: ["active"],
      where: {
        active: 1,
        pakage_id: 3,
        user_id: authUser.id,
      },
    });

    function setUndefinedIfNull(value) {
      return value === null ? undefined : value;
    }

    const FinalYearProjectUndefined = setUndefinedIfNull(FinalYearProject);
    const SiwesTechnicalReportUndefined =
      setUndefinedIfNull(SiwesTechnicalReport);
    const SeminarReportUndefined = setUndefinedIfNull(SeminarReport);

    req.token = sessionToken;
    req.user = authUser;
    req.subscriptions = {
      FinalYearProject: FinalYearProjectUndefined,
      SiwesTechnicalReport: SiwesTechnicalReportUndefined,
      SeminarReport: SeminarReportUndefined,
    };

    req.type = "student";
    next();
  } catch (e) {
    console.log(e);
    return renderErrorResponse(res);
  }
};

module.exports = auth;
