import models from "../../models/index.js";
import response from "../../response.js";
import {
  autoCalculateRoutes,
  autoGenerateLevelUpdateOtherRoutes,
} from "./checkLevel.js";

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

  try {
    const topic = await models.Topic.findByPk(ID_TOPIC);
    if (!topic) {
      return response(404, null, "Topic not found", res);
    }

    const { ID_SECTION } = topic;

    const levelNames = [
      "Pretest",
      "Level 1",
      "Level 2",
      "Level 3",
      "Level 4",
      "Level 5",
      "Level 6",
    ];

    const createdLevels = [];

    for (let i = 0; i < levelNames.length; i++) {
      const levelData = {
        ID_TOPIC,
        ID_SECTION,
        NAME_LEVEL: levelNames[i],
        IS_PRETEST: levelNames[i] === "Pretest" ? 1 : 0,
        CONTENT: null,
        AUDIO: null,
        IMAGE: null,
        VIDEO: null,
        ROUTE_1: 0,
        ROUTE_2: 0,
        ROUTE_3: 0,
        ROUTE_4: 0,
        ROUTE_5: 0,
        ROUTE_6: 0,
      };

      req.body = { ...levelData };
      await autoCalculateRoutes(req, res, () => {});

      const newLevel = await models.Level.create(req.body);
      createdLevels.push(newLevel);
    }

    await autoGenerateLevelUpdateOtherRoutes(req, res, createdLevels);

    const updatedLevels = await models.Level.findAll({
      where: {
        ID_TOPIC,
        IS_DELETED: 0,
      },
      order: [["NAME_LEVEL", "ASC"]],
    });

    res.locals.createdLevels = updatedLevels;

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