const express = require('express');
const path = require('path');
const { requireAuth, requireAdmin } = require('../middleware/auth');

// Import route modules
const authRoutes = require('./auth');
const locationRoutes = require('./locations');
const adminRoutes = require('./admin');
const settingsRoutes = require('./settings');
const userRoutes = require('./users');
const qrRoutes = require('./qr');
const debugRoutes = require('./debug');
const geocodingRoutes = require('../routes/geocoding'); // Existing geocoding routes
const shiftsRoutes = require('./shifts');

module.exports = (app) => {
    // Health check (no auth)
    app.get('/health', (req, res) => {
        res.json({ 
            status: 'healthy', 
            timestamp: new Date().toISOString(),
            version: process.env.npm_package_version || '1.0.0'
        });
    });
    
    // Login page (no auth)
    app.get('/login.html', (req, res) => {
        res.sendFile(path.join(__dirname, '../public', 'login.html'));
    });
    
    // Auth routes (no auth required)
    app.use('/api/auth', authRoutes);
    
    // Public config endpoint
    app.get('/api/config/start-location', require('../controllers/settingsController').getPublicStartLocation);
    
    // QR code routes (authenticated)
    app.use('/api/qr', requireAuth, qrRoutes);
    
    // Test QR page (no auth for testing)
    app.get('/test-qr', (req, res) => {
        res.sendFile(path.join(__dirname, '../public', 'test-qr.html'));
    });
    
    // Protected routes
    app.use('/api/locations', requireAuth, locationRoutes);
    app.use('/api/geocode', requireAuth, geocodingRoutes);
    app.use('/api/settings', requireAuth, settingsRoutes);
    app.use('/api/shifts', shiftsRoutes);
    
    // Admin routes
    app.get('/admin.html', requireAdmin, (req, res) => {
        res.sendFile(path.join(__dirname, '../public', 'admin.html'));
    });
    app.use('/api/admin', requireAdmin, adminRoutes);
    app.use('/api/users', requireAdmin, userRoutes);
    
    // Debug routes (admin only)
    app.use('/api/debug', requireAdmin, debugRoutes);
    
    // Config check endpoint (authenticated)
    app.get('/api/config-check', requireAuth, (req, res) => {
        const config = require('../config');
        
        const configStatus = {
            hasApiUrl: !!config.nocodb.apiUrl,
            hasApiToken: !!config.nocodb.apiToken,
            hasProjectId: !!config.nocodb.projectId,
            hasTableId: !!config.nocodb.tableId,
            hasLoginSheet: !!config.nocodb.loginSheetId,
            hasSettingsSheet: !!config.nocodb.settingsSheetId,
            projectId: config.nocodb.projectId,
            tableId: config.nocodb.tableId,
            loginSheet: config.nocodb.loginSheetId,
            settingsSheet: config.nocodb.settingsSheetId,
            nodeEnv: config.nodeEnv
        };
        
        const isConfigured = configStatus.hasApiUrl && 
                           configStatus.hasApiToken && 
                           configStatus.hasProjectId && 
                           configStatus.hasTableId;
        
        res.json({
            configured: isConfigured,
            ...configStatus
        });
    });
    
    // Config endpoint
    app.get('/api/config', (req, res) => {
        const config = require('../config');
        
        // Determine the MkDocs URL based on the request
        let mkdocsUrl = config.mkdocs.url;
        
        // If we're in production and the request is not from localhost
        if (config.isProduction && req.hostname !== 'localhost' && !req.hostname.includes('127.0.0.1')) {
            // Use the domain from config
            const mainDomain = config.domain;
            mkdocsUrl = `https://${mainDomain}`;
        }
        
        res.json({
            mkdocsUrl: mkdocsUrl,
            mkdocsPort: config.mkdocs.port
        });
    });
    
    // Serve static files (protected)
    app.use(express.static(path.join(__dirname, '../public'), {
        index: false // Don't serve index.html automatically
    }));
    
    // Main app route (protected)
    app.get('/', requireAuth, (req, res) => {
        res.sendFile(path.join(__dirname, '../public', 'index.html'));
    });
    
    // Protected page route
    app.get('/shifts.html', requireAuth, (req, res) => {
        res.sendFile(path.join(__dirname, '../public', 'shifts.html'));
    });
    
    // User profile page route
    app.get('/user.html', requireAuth, (req, res) => {
        res.sendFile(path.join(__dirname, '../public', 'user.html'));
    });
    
    // Catch all - redirect to login
    app.get('*', (req, res) => {
        res.redirect('/login.html');
    });
};