const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();

// Import the organizeFiles function from utils/organizeFiles.js
const organizeFiles = require('./utils/organizeFiles');

// Set port
const port = 5050;

// Middleware
app.use(express.json());

// Serve the index.html
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

// Directory where files are stored (private folder)
const privateFolderPath = path.join(__dirname, 'private');

// Organize files automatically when the server starts
try {
    organizeFiles(privateFolderPath);
} catch (error) {
    console.error('Error organizing files:', error);
}

// Routes
const uploadRoutes = require('./routes/upload');
const fileManagementRoutes = require('./routes/fileManagement');
const searchRoutes = require('./routes/search');
const downloadRoutes = require('./routes/download');

// Serve static files
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/private', express.static(path.join(__dirname, 'private')));

// Sanitize file names in 'private' on startup
const { sanitizeFilenames } = require('./utils/sanitize');
try {
    sanitizeFilenames(privateFolderPath);
} catch (error) {
    console.error('Error sanitizing filenames:', error);
}

// Register routes
app.use('/upload', uploadRoutes);
app.use('/files', fileManagementRoutes);
app.use('/search', searchRoutes);
app.use('/download', downloadRoutes);

// Handle Chrome DevTools request
app.get('/.well-known/appspecific/com.chrome.devtools.json', (req, res) => {
    res.status(200).json({});
});

// Handle 404 (not found) for undefined routes
app.use((req, res) => {
    console.log(`Route not found: ${req.method} ${req.originalUrl}`);
    res.status(404).send('Route not found');
});

// Start the server
app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
});