const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const helmet = require('helmet');
const compression = require('compression');
const rateLimit = require('express-rate-limit');
require('dotenv').config();

const authRoutes = require('./routes/auth.cjs');
const companyRoutes = require('./routes/company.cjs');
const clientRoutes = require('./routes/clients.cjs');
const supplierRoutes = require('./routes/suppliers.cjs');
const documentRoutes = require('./routes/documents.cjs');
const templateRoutes = require('./routes/templates.cjs');
const pdfRoutes = require('./routes/pdf.cjs');
const shareRoutes = require('./routes/share.cjs');
const serviceRoutes = require('./routes/services.cjs');
const requisitionRoutes = require('./routes/requisitions.cjs');
const publicPortal = require('./routes/public.cjs');
const app = express();

// Security middleware
app.use(helmet({
  contentSecurityPolicy: false, // Disable CSP temporarily to rule out blockages
  crossOriginResourcePolicy: { policy: "cross-origin" }
}));
app.use(compression());

// Rate limiting
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
});
app.use('/api/', limiter);

// CORS
app.use(cors({
  origin: process.env.CLIENT_URL || 'http://localhost:5173',
  credentials: true
}));

// Body parsing
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));


// Serve static files
app.use('/uploads', express.static('uploads'));
app.use('/pdfs', express.static('pdfs'));
app.use('/static', express.static(path.join(__dirname, 'public/static')));

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/company', companyRoutes);
app.use('/api/clients', clientRoutes);
app.use('/api/suppliers', supplierRoutes);
app.use('/api/documents', documentRoutes);
app.use('/api/templates', templateRoutes);
app.use('/api/pdf', pdfRoutes);
app.use('/api/share', shareRoutes);
app.use('/api/services', serviceRoutes);
app.use('/api/requisitions', requisitionRoutes);
app.use('/api/public', publicPortal);
// Important: mount WITHOUT /api prefix — public pages are clean URLs
app.use('/public', require('./routes/public.cjs'));
app.use('/api/public-portal-templates', require('./routes/public-portal-templates.cjs'));

// Health check
app.get('/api/health', (req, res) => {
  res.json({ status: 'OK', timestamp: new Date().toISOString() });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    message: 'Something went wrong!',
    error: process.env.NODE_ENV === 'development' ? err.message : {}
  });
});

// 404 handler
app.use('*', (req, res) => {
  res.status(404).json({ message: 'Route not found' });
});

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

// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/invoice-app')
  .then(() => {
    console.log('Connected to MongoDB');
    app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
    });
  })
  .catch((error) => {
    console.error('MongoDB connection error:', error);
    process.exit(1);
  });

module.exports = app;