const express = require('express');
const cors = require('cors');
require('dotenv').config();
const path = require('path');
const bodyParser = require("body-parser");
const { engine } = require("express-handlebars");
const handlebars = require("handlebars");
const compression = require("compression");
const helmet = require("helmet");

if (process.env.NODE_ENV === "dev") {
  process.removeAllListeners("warning");
}

// Routes
const apiAuthRoutes = require('./routes/apiAuth');
const webAuthRoutes = require('./routes/webAuth');
const mailboxRoutes = require('./routes/mailboxRoutes');
const domainRoutes = require('./routes/domainRoutes');
const statsRoutes = require('./routes/statsRoutes');

const app = express();
const port = process.env.PORT || 3000;
const ip = process.env.IP || '0.0.0.0';

// Middleware
app.use(bodyParser.json());
app.use(cors());
app.disable("x-powered-by");
app.set("trust proxy", "loopback");
app.set("view engine", "hbs");
app.use(helmet());

const hbsEngine = engine({
  layoutsDir: path.join(__dirname, "./views/layouts"),
  extname: "hbs",
  defaultLayout: "main",
  partialsDir: path.join(__dirname, "./views/partials"),
  helpers: {
    copyrightYear: () => new Date().getFullYear(),
    breadcrumb: function (options) {
      const url = options.data.root.currentUrl || "/";
      const parts = url.split("/").filter(Boolean);

      let breadcrumb = '<ol class="breadcrumb">';
      breadcrumb +=
        '<li class="breadcrumb-item"><a href="/">Dashboard</a></li>';

      let currentPath = "";
      for (let i = 0; i < parts.length; i++) {
        currentPath += "/" + parts[i];
        const isLast = i === parts.length - 1;

        breadcrumb += '<li class="breadcrumb-item';
        if (isLast) breadcrumb += ' active" aria-current="page';
        breadcrumb += '">';

        if (!isLast) {
          breadcrumb += `<a href="${currentPath}">${
            parts[i].charAt(0).toUpperCase() + parts[i].slice(1)
          }</a>`;
        } else {
          breadcrumb += parts[i].charAt(0).toUpperCase() + parts[i].slice(1);
        }

        breadcrumb += "</li>";
      }

      breadcrumb += "</ol>";
      return new handlebars.SafeString(breadcrumb);
    },
    section: function (name, options) {
      if (!this._sections) this._sections = {};
      this._sections[name] = options.fn(this);
      return null;
    },
  },
});

app.engine("hbs", hbsEngine);

app.disable("view cache");

app.set("views", path.join(__dirname, "./views"));

app.use(compression());
app.use("/public", express.static(path.join(__dirname, "./public")));
// Routes
app.use('/api/auth', apiAuthRoutes);
app.use('/auth', webAuthRoutes);
app.use('/api/mailboxes', mailboxRoutes);
app.use('/api/domains', domainRoutes);
app.use('/api/stats', statsRoutes);

app.get('/', (req, res) => {
  res.json({ message: 'API is running' });
});

// Error handling
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

const cron = require('node-cron');
const { cleanupOrphanedMailboxes, cleanupUnmatchedAndExpired, cleanupInactiveMailboxes } = require('./scripts/cleanup');
cron.schedule('0 0 * * *', async () => {
    console.log('Running mailbox cleanup job');
  try {
    await cleanupOrphanedMailboxes();
    await cleanupUnmatchedAndExpired();
    await cleanupInactiveMailboxes();
    console.log('Mailbox cleanup completed successfully');
  } catch (error) {
    console.error('Mailbox cleanup failed:', error);
  }
});

// Start server
app.listen(port, ip, () => {
  console.log(`API server listening on port ${port}`);
});