const express = require("express");
const cors = require("cors");
const swaggerUi = require("swagger-ui-express");

const tileRoutes = require("./routes/tiles");
const rasterTileRoutes = require("./routes/rasterTiles");
const geoRoutes = require("./routes/geometries");
const entityRoutes = require("./routes/entities");
const sectionRoutes = require("./routes/sections");
const { openApiSpec } = require("./swagger");
const { envelopeResponses } = require("./utils/apiEnvelope");

const app = express();

app.use(cors());
app.use(express.json());

// serve MBTiles and geometry CRUD
app.use("/tiles", envelopeResponses, tileRoutes);
app.use("/raster-tiles", envelopeResponses, rasterTileRoutes);
app.use("/geometries", envelopeResponses, geoRoutes);
app.use("/entities", envelopeResponses, entityRoutes);
app.use("/sections", envelopeResponses, sectionRoutes);
app.use("/submissions", envelopeResponses, (req, res, next) => {
    req.url = `/submissions${req.url}`;
    sectionRoutes(req, res, next);
});
app.use("/docs", swaggerUi.serve, swaggerUi.setup(openApiSpec, {
    explorer: true,
}));
app.get("/docs.json", (req, res) => {
    res.json(openApiSpec);
});

app.get("/", (req, res) => {
    res.send("GIS server running");
});

app.listen(3000, () => {
    console.log("🚀 http://localhost:3000");
    console.log("📘 Swagger UI: http://localhost:3000/docs");
});
