import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { testConnection } from './config/database.js';

import authRoutes from './routes/auth.js';
import customerRoutes from './routes/customers.js';
import activityRoutes from './routes/activities.js';
import salesmenRoutes from './routes/salesmen.js';
import categoryRoutes from './routes/categories.js';
import { authenticateToken } from './middleware/auth.js';
import { getAllUsers } from './controllers/authController.js';

dotenv.config();

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

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

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

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

app.use('/api/auth', authRoutes);
app.use('/api/customers', customerRoutes);
app.use('/api/activities', activityRoutes);
app.use('/api/salesmen', salesmenRoutes);
app.use('/api/categories', categoryRoutes);
app.get('/api/users', authenticateToken, getAllUsers);

app.get('/', (req, res) => {
  res.json({
    message: 'Hireloom Global CRM API',
    version: '1.0.0',
    endpoints: {
      auth: '/api/auth',
      customers: '/api/customers',
      activities: '/api/activities',
      salesmen: '/api/salesmen',
      categories: '/api/categories'
    }
  });
});

app.use((err, req, res, next) => {
  console.error('Error:', err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

const startServer = async () => {
  try {
    await testConnection();

    app.listen(PORT, () => {
      console.log(`🚀 Server is running on port ${PORT}`);
      console.log(`📊 API Documentation: http://localhost:${PORT}`);
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
};

startServer();
