const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");

const errorMiddleware = require("./server/middlewares/error-middleware");

const environment = process.env.NODE_ENV || "development";
console.log(`Environment ${environment}`);
require("dotenv").config({ path: `.env.${environment}` });

const routers = require("./server/routers/routers");
const routersV2 = require("./server/routers/routers-v2");
const firebaseService = require("./server/services/notifications/firebase-notifications-service"); // путь к твоему файлу инициализации

const PORT = process.env.PORT || 5000;
const ENVNAME = process.env.NAME || "No enviroment name";

const app = express();

const corsOptions = {
  origin: [
    "http://localhost:5105",
    "http://localhost:5106",
    "https://admin-panel-dev.zinglez.app",
    "https://admin-panel-staging.zinglez.app",
    "https://admin-panel.zinglez.app",
    "https://zinglez.app",
  ],
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
  exposedHeaders: ["X-Total-Count"],
  credentials: true,
};

app.use(cors(corsOptions));
app.options("*", cors(corsOptions));

app.use(express.json());

app.use("/api/v1", routers);
app.use("/api/v2", routersV2);

app.use(errorMiddleware);

const start = async () => {
  try {
    await mongoose.connect(process.env.DB_URL, { autoIndex: true });

    const { db } = mongoose.connection;

    const indexes = await db.collection("users").indexes();
    console.log("Indexes:", indexes);

    const indexExists = indexes.some(
      (index) => index.name === "currentLocation_2dsphere",
    );

    if (indexExists) {
      await db.collection("users").dropIndex("currentLocation_2dsphere");
    } else {
      console.log("Index currentLocation_2dsphere does not exist.");
    }

    //Init Firebase for PN
    firebaseService.init();

    app.listen(PORT, () =>
      console.log(
        `Server stared on port = ${PORT} for ${ENVNAME} DB: ${process.env.DB_URL}`,
      ),
    );
  } catch (error) {
    console.log(error);
  }
};

require("./server/jobs/jobs");

start();
