import express from 'express';
import { logger } from './logger.js';

/**
 * Serve static files from the STATIC_PATH environment variable.
 * If STATIC_PATH is not set, log a warning and do not serve static files.
 * 
 * Should be called after all other routes are defined. Otherwise, it will
 * interfere with the API routes due to the catch-all route.
 * 
 * @param {express.Express} app - The Express application instance.
 * @param {string} staticPath - The path to the static files.
 * @returns {void}
 */
export function serveStatic(app, staticPath) {
    logger.info(`Serving static files from ${staticPath}`);
    app.use(express.static(staticPath));

    // Serve index.html for all other routes
    app.get('/*all', (req, res) => {
        res.sendFile(`${staticPath}/index.html`, (err) => {
            if (err) {
                logger.error(`Error serving index.html: ${err}`);
                res.status(err.status).end();
            }
        });
    });
}
