const { applyMiddlewares } = require('../middlewares');
const { renderRoutes } = require('../routes/index');
const removeImages = require('./remove-images');
const fs = require('fs');
const path = require('path');
const { endpoints, UPLOAD_FS_DIR, PREVIEW_FS_DIR } = require('../constants');


const initiateResources = (app) => {
    applyMiddlewares(app);

    renderRoutes(app);

    // Ensure upload images directory exists
    // In test mode, UPLOAD_FS_DIR is absolute (/tmp/...), otherwise relative (data/images)
    const imagesDir = path.isAbsolute(UPLOAD_FS_DIR) 
        ? UPLOAD_FS_DIR 
        : path.join(__dirname, '..', UPLOAD_FS_DIR);
    if (!fs.existsSync(imagesDir)){
        fs.mkdirSync(imagesDir, { recursive: true });
    }

    // Ensure preview images directory exists
    const previewsDir = path.isAbsolute(PREVIEW_FS_DIR)
        ? PREVIEW_FS_DIR
        : path.join(__dirname, '..', PREVIEW_FS_DIR);
    if (!fs.existsSync(previewsDir)){
        fs.mkdirSync(previewsDir, { recursive: true });
    }

    // Ensure db directory exists: backend/src/../data/db
    const dbDir = path.join(__dirname, '..', 'data', 'db');
    if (!fs.existsSync(dbDir)){
        fs.mkdirSync(dbDir, { recursive: true });
    }

    if(process.env.REMOVE_IMAGES === 'true') {
        removeImages();
    };
};

module.exports = initiateResources;