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

// Helper function to parse NocoDB URLs
function parseNocoDBUrl(url) {
    if (!url) return { projectId: null, tableId: null };
    
    const patterns = [
        /#\/nc\/([^\/]+)\/([^\/\?#]+)/,
        /\/nc\/([^\/]+)\/([^\/\?#]+)/,
        /project\/([^\/]+)\/table\/([^\/\?#]+)/,
    ];
    
    for (const pattern of patterns) {
        const match = url.match(pattern);
        if (match) {
            return {
                projectId: match[1],
                tableId: match[2]
            };
        }
    }
    
    return { projectId: null, tableId: null };
}

// Auto-parse IDs from URLs
let parsedIds = { projectId: null, tableId: null };
if (process.env.NOCODB_VIEW_URL && (!process.env.NOCODB_PROJECT_ID || !process.env.NOCODB_TABLE_ID)) {
    parsedIds = parseNocoDBUrl(process.env.NOCODB_VIEW_URL);
}

// Parse login sheet ID
let loginSheetId = null;
if (process.env.NOCODB_LOGIN_SHEET) {
    if (process.env.NOCODB_LOGIN_SHEET.startsWith('http')) {
        const { tableId } = parseNocoDBUrl(process.env.NOCODB_LOGIN_SHEET);
        loginSheetId = tableId;
    } else {
        loginSheetId = process.env.NOCODB_LOGIN_SHEET;
    }
}

// Parse settings sheet ID
let settingsSheetId = null;
if (process.env.NOCODB_SETTINGS_SHEET) {
    if (process.env.NOCODB_SETTINGS_SHEET.startsWith('http')) {
        const { tableId } = parseNocoDBUrl(process.env.NOCODB_SETTINGS_SHEET);
        settingsSheetId = tableId;
    } else {
        settingsSheetId = process.env.NOCODB_SETTINGS_SHEET;
    }
}

// Parse shifts sheet ID
let shiftsSheetId = null;
if (process.env.NOCODB_SHIFTS_SHEET) {
    if (process.env.NOCODB_SHIFTS_SHEET.startsWith('http')) {
        const { tableId } = parseNocoDBUrl(process.env.NOCODB_SHIFTS_SHEET);
        shiftsSheetId = tableId;
    } else {
        shiftsSheetId = process.env.NOCODB_SHIFTS_SHEET;
    }
}

// Parse shift signups sheet ID
let shiftSignupsSheetId = null;
if (process.env.NOCODB_SHIFT_SIGNUPS_SHEET) {
    if (process.env.NOCODB_SHIFT_SIGNUPS_SHEET.startsWith('http')) {
        const { tableId } = parseNocoDBUrl(process.env.NOCODB_SHIFT_SIGNUPS_SHEET);
        shiftSignupsSheetId = tableId;
    } else {
        shiftSignupsSheetId = process.env.NOCODB_SHIFT_SIGNUPS_SHEET;
    }
}

module.exports = {
    // Server config
    port: process.env.PORT || 3000,
    nodeEnv: process.env.NODE_ENV || 'development',
    isProduction: process.env.NODE_ENV === 'production',
    domain: process.env.DOMAIN || 'cmlite.org', // Add this
    
    // NocoDB config
    nocodb: {
        apiUrl: process.env.NOCODB_API_URL,
        apiToken: process.env.NOCODB_API_TOKEN,
        projectId: process.env.NOCODB_PROJECT_ID || parsedIds.projectId,
        tableId: process.env.NOCODB_TABLE_ID || parsedIds.tableId,
        loginSheetId,
        settingsSheetId,
        viewUrl: process.env.NOCODB_VIEW_URL,
        shiftsSheetId,
        shiftSignupsSheetId
    },
    
    // Session config
    session: {
        secret: process.env.SESSION_SECRET || 'your-secret-key-change-in-production',
        cookieDomain: process.env.COOKIE_DOMAIN
    },
    
    // CORS config
    cors: {
        allowedOrigins: process.env.ALLOWED_ORIGINS?.split(',') || []
    },
    
    // Map defaults
    map: {
        defaultLat: parseFloat(process.env.DEFAULT_LAT) || 53.5461,
        defaultLng: parseFloat(process.env.DEFAULT_LNG) || -113.4938,
        defaultZoom: parseInt(process.env.DEFAULT_ZOOM) || 11,
        bounds: process.env.BOUND_NORTH ? {
            north: parseFloat(process.env.BOUND_NORTH),
            south: parseFloat(process.env.BOUND_SOUTH),
            east: parseFloat(process.env.BOUND_EAST),
            west: parseFloat(process.env.BOUND_WEST)
        } : null
    },
    
    // MkDocs configuration
    mkdocs: {
        url: process.env.MKDOCS_URL || `http://localhost:${process.env.MKDOCS_SITE_SERVER_PORT || '4002'}`,
        searchUrl: process.env.MKDOCS_SEARCH_URL || `http://localhost:${process.env.MKDOCS_SITE_SERVER_PORT || '4002'}`,
        port: process.env.MKDOCS_SITE_SERVER_PORT || '4002'
    },
    
    // Utility functions
    parseNocoDBUrl
};