const dotenv = require('dotenv');
dotenv.config();

/**
 * Formats a relative path into an absolute URL for mobile/third-party access.
 * If the path is already an absolute URL (starts with http/https), it returns it as is.
 * 
 * @param {string} relativePath - The relative path to the file (e.g., /uploads/avatar.png)
 * @returns {string} - The absolute URL
 */
const getAbsoluteUrl = (relativePath) => {
    if (!relativePath) return null;
    
    // If it's already an absolute URL, return it
    if (relativePath.startsWith('http://') || relativePath.startsWith('https://')) {
        return relativePath;
    }

    // Ensure we have a base URL. Fallback to a sensible default if CLIENT_ORIGIN is missing.
    // NOTE: In production, API_BASE_URL should be set in .env
    const baseUrl = process.env.API_BASE_URL || process.env.API_URL || process.env.CLIENT_ORIGIN || 'https://infoseclabs.io';
    
    // Ensure relativePath starts with /
    const normalizedPath = relativePath.startsWith('/') ? relativePath : '/' + relativePath;
    
    // Remote trailing slash from baseUrl if present
    const cleanBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
    
    return `${cleanBaseUrl}${normalizedPath}`;
};

/**
 * Formats a user object, converting relative image paths to absolute URLs.
 * 
 * @param {object} user - The user object from database
 * @returns {object} - The formatted user object
 */
const formatUserUrls = (user) => {
    if (!user) return user;
    
    const formatted = { ...user };
    
    if (formatted.profile_picture) {
        formatted.profile_picture = getAbsoluteUrl(formatted.profile_picture);
    }
    
    if (formatted.avatar) { // Used in some leaderboard responses
        formatted.avatar = getAbsoluteUrl(formatted.avatar);
    }
    
    if (formatted.banner_url) {
        formatted.banner_url = getAbsoluteUrl(formatted.banner_url);
    }
    
    return formatted;
};

module.exports = {
    getAbsoluteUrl,
    formatUserUrls
};
