// apps/api/src/app.js

const path = require('path');
try {
    require('dotenv').config({ path: path.join(__dirname, '..', '..', '.env') });
} catch (error) {
    // Vercel provides environment variables without dotenv
}

const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
// const rateLimit = require('express-rate-limit');

const authRoutes = require('./routes/auth.routes');
const leadsRoutes = require('./routes/leads.routes');
const searchRoutes = require('./routes/search.routes');
const scrapeRoutes = require('./routes/scrape.routes');
const adminRoutes = require('./routes/admin.routes');
const bookmarksRoutes = require('./routes/bookmarks.routes');
const healthRoutes = require('./routes/health.routes');
const errorMiddleware = require('./middleware/error.middleware');
const billingRoutes = require('./routes/billing.routes');

const app = express();

// Security middleware
app.use(helmet());
app.use(cors({
    origin: process.env.FRONTEND_URL || 'http://localhost:3000',
    credentials: true
}));

// Body parsing
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/leads', leadsRoutes);
app.use('/api/search', searchRoutes);
app.use('/api/scrape', scrapeRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/bookmarks', bookmarksRoutes);
app.use('/api/health', healthRoutes);
app.use('/api/billing', billingRoutes);

// Error handling
app.use(errorMiddleware);

module.exports = app;