import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import { testConnection } from "./database/db.js";
import router from "./routes/index.js";
import cookieParser from "cookie-parser";
import promBundle from "express-prom-bundle";
import cron from "node-cron";
import models from "./models/index.js";

dotenv.config();
const app = express();

const metricsMiddleware = promBundle({
  includeMethod: true,
  includePath: true,
  includeStatusCode: true,
  promClient: {
    collectDefaultMetrics: {},
  },
});

app.use(metricsMiddleware);

const corsOptions = {
  origin: `${process.env.CLIENT_URL}`,
  methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
  allowedHeaders: ["Content-Type", "Authorization"],
  credentials: true,
};

app.use(cors(corsOptions));

app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(router);
app.use(express.static("public"));

cron.schedule("0 0 * * *", async () => {
  const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
  const transaction = await models.db.transaction();

  try {
    const unvalidatedUsers = await models.User.findAll({
      attributes: ["ID"],
      where: {
        IS_VALIDATED: 0,
        TIME_USERS: { [models.Sequelize.Op.lt]: oneDayAgo },
      },
      transaction,
    });

    const unvalidatedUserIDs = unvalidatedUsers.map((user) => user.ID);

    if (unvalidatedUserIDs.length > 0) {
      await models.Student.destroy({
        where: { ID: { [models.Sequelize.Op.in]: unvalidatedUserIDs } },
        transaction,
      });

      await models.Teacher.destroy({
        where: { ID: { [models.Sequelize.Op.in]: unvalidatedUserIDs } },
        transaction,
      });

      await models.User.destroy({
        where: {
          ID: { [models.Sequelize.Op.in]: unvalidatedUserIDs },
        },
        transaction,
      });
    }

    await transaction.commit();
    console.log(
      "Removed unvalidated users and their related data registered over 1 day ago."
    );
  } catch (error) {
    await transaction.rollback();
    console.error(
      "Failed to delete unvalidated users and related data:",
      error
    );
  }
});

app.listen(process.env.APP_PORT, () => {
  testConnection();
  console.log(`Server running on port ${process.env.APP_PORT}`);
});
