import cors from "cors"
import mongoose from "mongoose"
import *as dotenv from "dotenv"
import express from "express"
import PostRouter from "./routes/Posts.js"
import GenerateImageRouter from "./routes/ImageGenerate.js"


dotenv.config();

const app = express();
app.use(cors());
app.use(express.json({limit: "50mb"}));
app.use(express.urlencoded({extended: true}));
app.use((err, req, res, next) => { 
    const status = err.status || 500;
    const message = err.message || "Error!!"
    return res.status(status).json(
        { 
            success: false, 
            status, 
            message 
        }
    ) 
});

app.use("/api/post", PostRouter);
app.use("/api/generateImage", GenerateImageRouter)


app.get("/", async(req, res) => {
    res.status(200).json({
        message: "Test"
    })
});

//connect with MongoDB
const connectDB = () => {
    mongoose.set("strictQuery", true);
    mongoose.connect(process.env.MONGODB_URL).then(() => console.log("MongoDB connected")).catch((err) => {
        console.error("Failed to connect with MongoDB");
        console.error(err);
    })
}


//start server
const startServer = async () => {
    try {
        app.listen(8080, () => console.log("Server is running on port 8080"))
        connectDB();
    } catch (error) {
        console.log(error)
    }
};
startServer()

