const express = require("express");
const cors = require("cors");
require("dotenv").config();
const userRouter = require("./router/user");
const path = require("path");
const fileupload = require("express-fileupload");
const postRouter = require("./router/post");
const missionRouter = require("./router/mission");
const http = require('http');
const {TextDecoder, TextEncoder} = require("util");
const connectDB = require("./db");
connectDB();

const app = express();
const chatServer = http.createServer(app);
app.use(cors());
app.use(express.json());
app.use(
  fileupload({
    limits: { fileSize: 2 * 1024 * 1024 }, // 2mb
    abortOnLimit: true, // if limit is reached return 413
    createParentPath: true,
    useTempFiles: true,
  })
);



app.use("/api/user", userRouter);
app.use("/api/post", postRouter);
app.use("/api/mission", missionRouter);


// const port = process.env.PORT;
// app.listen(port, () => {
//   console.log(`server is running 0n localhost:${port}`);
// });

const PORT = process.env.PORT || 5000;


const server = chatServer.listen(PORT,
    console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`.blue));

// Handle unhandled promise rejection
process.on('unhandledRejection', (err, promise) => {
    console.log(`Error: ${err.message}`);
    //close server and exit process
    server.close(() => process.exit(1));
});

app.use('*', (req, res) => {
    res.status(404, {
        message: 'NOT FOUND'
    })
});