// Initialize .env file
require('dotenv').config()

const express = require("express");
const app = express();
const cors = require("cors");
const router = require("./routes/routes");
const sequelize = require('./config/sequelize');



const path = require('path');
app.use('/uploads', express.static('uploads'));



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


// this is a package need to install when we are calling the below apis from frontend application via fetch or axios etc.
app.use(cors())

// body parser for getting json body on a server (always place on top of al apis )
app.use(express.json())
app.use(express.urlencoded({ extended: true }));


// Initialize database connection and tables
(async () => {
    try {
        // Test connection
        await sequelize.authenticate();
        console.log('Database connection established successfully.');

        // Sync all models
        // Note: force: false means it won't drop tables if they exist
        // Use { force: true } during development if you want to recreate tables
        await sequelize.sync({ force: false });
        console.log('Database models synchronized successfully.');
    } catch (error) {
        console.error('Error initializing database:', error);
    }
})();

// middleware that listen every request which hits on this server. It tells that whenever you recieve /api form frontend in any api got to this router function
app.use("/api", router)

app.listen(PORT, () => console.log(`server is running on localhost: ${PORT}`))
