import express from 'express';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import userRouter from './routes/user.route.js';
import authRouter from './routes/auth.route.js';
import listingRouter from './routes/listing.route.js'
import cookieParser from 'cookie-parser';


dotenv.config();

//connect with MongoDB
mongoose.connect(process.env.MONGODB).then(() => {
    console.log('Connected to MongoDB')
}).catch((error) => {
    console.log(error)
})

//connect with Express
const app = express();

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

app.listen(3000, () =>{
    console.log('Server is running on port 3000')
})

//create api route
app.use('/server/user', userRouter)
app.use('/server/auth', authRouter)
app.use('/server/listing', listingRouter)

//middleware to catch an error
app.use((err, req, res, next) => {
    const statusCode = err.statusCode || 500
    const message = err.message || "Internal server error"
    return res.status(statusCode).json({
        success: false,
        statusCode,
        message,
    })
})
