const jwt = require("jsonwebtoken");
const { users, profiles, subscriptions, departments, institutes, study_modes, sessions } = require("../../models");
const session = require("express-session");

const renderErrorResponse = (res) => {
  return res.redirect("https://portal.kwarastatepolytechnic.edu.ng/login.php")
  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;
    }

    const authUser = await users.findOne({
      where: {
        username: decoded.username,
      },
      include: [
        {
          model: profiles,
          include: [
            {
              model: users,
              attributes: ["username"],
            },
            {
              model: study_modes,
              attributes: ["name"],
            },
            {
              model: departments,
              attributes: ["id", "name"],
              include: [
                {
                  model: institutes,
                  attributes: ["name"],
                },
              ],
            },
            {
              model: sessions, 
              attributes: ["status", "ft_status","pt_status"]
            }
          ],
        },
      ],
    });

    if (!authUser) {
      return renderErrorResponse(res);
    }

    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 = JSON.parse(JSON.stringify(authUser));
    req.profile = authUser.profile;
    req.subscriptions = {
      FinalYearProject: FinalYearProjectUndefined,
      SiwesTechnicalReport: SiwesTechnicalReportUndefined,
      SeminarReport: SeminarReportUndefined,
    };

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

module.exports = auth;
