import express from 'express';
import cors from 'cors';
import path from 'path';
import authRoutes from './routes/authRoutes.js';
import dashboardRoutes from './routes/dashboardRoutes.js';
import usermanagementRoutes from './routes/usermanagementRoutes.js';
import accountantRoutes from './routes/accountantRoutes.js';
import invoiceRoutes from './routes/invoiceRoutes.js';
import billRoutes from './routes/billRoutes.js';
import expenseRoutes from './routes/expenseRoutes.js';
import salaryRoutes from './routes/salaryRoutes.js';
import domainmanagementRoutes from './routes/domainmanagementRoutes.js';
import hostingRoutes from './routes/hostingRoutes.js';
import morgan from 'morgan';
import { requirePermission } from './middleware/authMiddleware.js';
// import Lead from './models/leadmanagement.model.js';
import leadmanagementRoutes from './routes/leadmanagementRoutes.js'
import clientmanagementRoutes from './routes/clientmanagementRoutes.js';
import settingsRoutes from './routes/settingsRoutes.js';

const app = express();

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

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/uploads', express.static(path.join(process.cwd(), 'uploads')));
app.get('/', (req, res) => {
    res.status(200).json({
        success: true,
        message: 'Server started successfully'
    });
});

// routes
app.use('/api/auth', authRoutes);
app.use('/api/dashboard', requirePermission('dashboard'), dashboardRoutes);
app.use('/api/users', requirePermission('user'), usermanagementRoutes); //done
app.use('/api/accountants', requirePermission('accountant'), accountantRoutes); //done
app.use('/api/invoices', requirePermission('invoice'), invoiceRoutes); //done
app.use('/api/bills', requirePermission('bill'), billRoutes); //done
app.use('/api/expenses', requirePermission('expenses'), expenseRoutes); //done
app.use('/api/salaries', requirePermission('salary'), salaryRoutes);//done
app.use('/api/domains', requirePermission('domain'), domainmanagementRoutes); //done
app.use('/api/hostings', requirePermission('hosting'), hostingRoutes); //done
app.use('/api/leads', leadmanagementRoutes); //done
app.use('/api/clients', clientmanagementRoutes); //done
app.use('/api/settings', settingsRoutes);
app.use((req, res) => {
    res.status(404).json({
        success: false,
        message: `Route not found: ${req.method} ${req.originalUrl}`
    });
});

export default app;
