const dotenv = require("dotenv");
dotenv.config();
// const { createApp } = require("validation_package_build");
const { createApp } = require("whoxa_web_setup");
const {
  UserSocket,
  Admin,
  App_Flow,
  App_Setting,
  Group_Setting,
  Language_status,
  Language_setting,
  One_signal_setting,
  Website_Setting,
  sequelize
} = require("./models");
const Sequelize = require("sequelize");

const no_auth_route = require("./routes/NoAuthRoutes");
const auth_routes = require("./routes/AuthRoutes");
const admin_routes = require("./routes/Admin.routes");
const socketService = require("./reusable/socketService");

const removePinMessage = require("./controller/Chat/StarMessage/removePinMessage");
const { removeStatusAfter24Hours } = require("./controller/Status/removeStatusAfter24Hours");
const { addLanguageColumn } = require("./reusable/add_new_language");
// import myRoutes from "./routes/myRoutes";
async function fetchLanguages() {
  try {
    const all_Languages = await Language_status.findAll();
    const languagelist = all_Languages.map((lang) => {
      return lang.dataValues.language;
    });
    return languagelist;
    // console.log(languagelist);
  } catch (error) {
    console.error("Error fetching languages:", error);
  }
}

async function startServer() {
  try {


    const { app, server, io } = await createApp({
      enableSocket: true,
      jwtSecret: process.env.JWT_SECRET_KEY,
      models: {
        UserSocket: UserSocket,
        Admin: Admin,
        App_Flow: App_Flow,
        App_Setting: App_Setting,
        Group_Setting: Group_Setting,
        Language_status: Language_status,
        Language_setting: Language_setting,
        One_signal_setting: One_signal_setting,
        Website_Setting: Website_Setting,
      },
      language_functions: {
        fetchLanguages: fetchLanguages,
        addLanguageColumn: addLanguageColumn
      },
      sequelize: sequelize,
      Sequelize: Sequelize,
      product_type: "web",
      // myRoutes: myRoutes,
      routes: { no_auth_route: no_auth_route, auth_routes: auth_routes, admin_routes: admin_routes },

      onSocketConnect: (io) => socketService.initSocket(io),

      cronJobs: [
        {
          schedule: "0 * * * *", // every day at 9 AM
          job: () => {
            removeStatusAfter24Hours();
            removePinMessage();
          },
        },

      ]
    });
    if (io) {
      console.log("Socket.IO path =>", io._opts?.path || io.opts?.path);
    }
    else {
      console.log("not configured");

    }


    await sequelize.sync({ force: false });
    server.listen(3000, () => console.log("Server running on 3000"));
  } catch (error) {
    console.log("error", error);

  }
}

startServer().catch((err) => {
  console.error("Failed to start server:", err);
});
