import express from 'express';
import cors from 'cors';
import { connectDB } from './config/db.js';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import userRoute from './routes/userRoute.js';
import adminRoute from './routes/adminRoute.js';
import { fileURLToPath } from 'url';
import path from 'path';
import { errorHandler } from './middlewares/errorHandler.js';
import categoryRoute from './routes/categoryRoute.js';
import productRoute from './routes/productsRoute.js';


dotenv.config();

// Setup __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// App config
const app = express();
const port = process.env.PORT || 9000;

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(errorHandler)
app.use("/uploads", express.static("uploads"));

//  CORS setup
const allowedOrigins = [
    'http://localhost:5173', // Vite dev
    'http://128.199.24.208', // Your DigitalOcean IP (for testing)
];

app.use(
    cors({
        origin: (origin, callback) => {
            if (!origin || allowedOrigins.includes(origin)) {
                callback(null, true);
            } else {
                callback(new Error('Not allowed by CORS'));
            }
        },
        credentials: true,
    })
);

// API endpoints
app.use('/api', userRoute, adminRoute);
app.use('/api/category', categoryRoute);
app.use('/api/product', productRoute)


//  Serve Vite React frontend in production
const buildPath = path.join(__dirname, '../frontend/dist');

if (process.env.NODE_ENV === 'production') {
    app.use(express.static(buildPath));

    
    app.get((req, res) => {
        res.sendFile(path.resolve(buildPath, 'index.html'));
    });
}

// Default route (useful for testing backend)
app.get('/', (req, res) => {
    res.send('Backend running successfully 🚀');
});

// Start server
app.listen(port, () => {
    connectDB();
    console.log(`Server started on http://localhost:${port}`);
});
