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

export const checkStdLearning = async (req, res, next) => {
  const { ID_LEVEL } = req.body;

  if (!req.user) {
    return response(401, null, "User not authenticated", res);
  }

  if (!ID_LEVEL) {
    return response(400, null, "Level ID is required", res);
  }

  const ID = req.user.ID;

  try {
    const existingStdLearning = await models.StdLearning.findOne({
      where: {
        ID: ID,
        ID_LEVEL: ID_LEVEL,
      },
    });

    if (existingStdLearning && existingStdLearning.SCORE === null) {
      req.stdLearning = existingStdLearning;
      return next();
    }

    return next();
  } catch (error) {
    console.log(error);
    return response(500, null, "Internal Server Error", res);
  }
};
