import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';

import authRoutes from './routes/auth.js';
import memberRoutes from './routes/member.js';
import adminRoutes from './routes/admin.js';
import walletRoutes from './routes/wallet.js';
import salaryRoutes from './routes/Salaryroutes.js';

dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

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

app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

app.use('/api/auth', authRoutes);
app.use('/api/members', memberRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/wallet', walletRoutes);
app.use('/api/admin/salary', salaryRoutes);

app.get('/', (req, res) => {
  res.json({
    success: true,
    message: 'MLM Backend API Server',
    version: '1.0.0',
    endpoints: {
      auth: '/api/auth',
      members: '/api/members',
      customers: '/api/customers',
      products: '/api/products',
      orders: '/api/orders',
      admin: '/api/admin',
      wallet: '/api/wallet'
    }
  });
});

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

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
  console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
});

export default app;