const express = require('express');
const cors = require('cors');
require('dotenv').config();

const authRoutes = require('./routes/authRoutes');
const dashboardRoutes = require('./routes/dashboardRoutes');
const userRoutes = require('./routes/userRoutes');
const companyRoutes = require('./routes/companyRoutes');
const applicationRoutes = require('./routes/applicationRoutes');
const txnCategoryRoutes = require('./routes/txnCategoryRoutes');
const invoiceRoutes = require('./routes/invoiceRoutes');
const transactionRoutes = require('./routes/transactionRoutes');
const customerRoutes = require('./routes/customerRoutes');
const paymentAccountRoutes = require('./routes/paymentAccountRoutes');
const leadRoutes = require('./routes/leadRoutes');
const agreementRoutes = require('./routes/agreementRoutes');
const taskRoutes = require('./routes/taskRoutes');
const productRoutes = require('./routes/productRoutes');
const { isMockDB } = require('./config/db');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 5000;

// Middleware
app.use(cors({
  origin: '*', // Allow frontend dev server
  credentials: true,
}));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));

// Serve Static Uploads
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// Health Check
app.get('/api/health', (req, res) => {
  res.json({
    status: 'online',
    timestamp: new Date(),
    databaseMode: isMockDB() ? 'Mock Database Fallback' : 'MySQL Live Database',
  });
});

// Register API Routes
app.use('/api/auth', authRoutes);
app.use('/api/dashboard', dashboardRoutes);
app.use('/api/users', userRoutes);
app.use('/api/company', companyRoutes);
app.use('/api/applications', applicationRoutes);
app.use('/api/txn-categories', txnCategoryRoutes);
app.use('/api/invoices', invoiceRoutes);
app.use('/api/transactions', transactionRoutes);
app.use('/api/customers', customerRoutes);
app.use('/api/payment-accounts', paymentAccountRoutes);
app.use('/api/leads', leadRoutes);
app.use('/api/agreements', agreementRoutes);
app.use('/api/tasks', taskRoutes);
app.use('/api/products', productRoutes);

// Global Error Handler
app.use((err, req, res, next) => {
  console.error('API Error:', err.stack);
  res.status(500).json({
    success: false,
    message: 'An unexpected server error occurred.',
    error: err.message,
  });
});

// Start Server
app.listen(PORT, () => {
  console.log(`==================================================`);
  console.log(`🚀 Express Backend Server running on http://localhost:${PORT}`);
  console.log(`🔐 Auth API: http://localhost:${PORT}/api/auth`);
  console.log(`📊 Dashboard API: http://localhost:${PORT}/api/dashboard`);
  console.log(`👥 Users API: http://localhost:${PORT}/api/users`);
  console.log(`🏢 Company API: http://localhost:${PORT}/api/company`);
  console.log(`📱 Applications API: http://localhost:${PORT}/api/applications`);
  console.log(`🏷️ Transaction Categories API: http://localhost:${PORT}/api/txn-categories`);
  console.log(`📄 Invoices API: http://localhost:${PORT}/api/invoices`);
  console.log(`💳 Transactions API: http://localhost:${PORT}/api/transactions`);
  console.log(`🎯 Leads API: http://localhost:${PORT}/api/leads`);
  console.log(`📦 Products API: http://localhost:${PORT}/api/products`);
  console.log(`==================================================`);
});


