// SLM Framework API - Configuration
const { exec } = require('child_process');
const md5 = require('md5');
const fs = require('fs');
const bcrypt = require('bcrypt');
const moment = require('moment-timezone');

// Load environment variables from local .env
require('dotenv').config();

// Set default timezone and locale
moment.tz.setDefault(process.env.TZ || 'America/Mexico_City');
moment.locale('es');

// Load Elasticsearch service
const elasticsearch = require('./elasticsearch.slm');

// Database configuration
const es_server = process.env.ES_SERVER || "http://elasticsearch:9200";
const es_index = process.env.DEV_ES_INDEX || "slm-app-dev";
const es_index_log = `${es_index}-api-log`;

// API Configuration
const api_version = "1.0.0";
const api_name = "SLM Framework API";

// Security
const api_keys = [
    'dev-key-12345',
    'test-key-67890'
];

// Rate limiting
const rate_limit_enabled = true;
const rate_limit_max = 100;      // requests per window
const rate_limit_window = 60;    // seconds

/**
 * Get current timestamp in different formats
 * @param {string} tz - Timezone ('mx' for Mexico, default UTC)
 */
function now(tz) {
    if (tz === "mx") {
        moment.locale('es');
        return moment().tz('America/Mexico_City').format('YYYY-MM-DD HH:mm:ss');
    }
    return moment().toISOString();
}

/**
 * Get timestamp in milliseconds
 */
function timestamp() {
    return Date.now();
}

/**
 * Format date using moment.js
 * @param {string|number|Date} date - Date to format
 * @param {string} format - Format string (default: 'YYYY-MM-DD HH:mm:ss')
 */
function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
    return moment(date).format(format);
}

/**
 * Get relative time (e.g., "hace 2 horas")
 * @param {string|number|Date} date - Date to compare
 */
function fromNow(date) {
    moment.locale('es');
    return moment(date).fromNow();
}

module.exports = {
    // Utilities
    exec,
    md5,
    fs,
    bcrypt,
    moment,

    // Date functions
    now,
    timestamp,
    formatDate,
    fromNow,

    // Configuration
    es_server,
    es_index,
    es_index_log,
    api_version,
    api_name,
    api_keys,
    rate_limit_enabled,
    rate_limit_max,
    rate_limit_window,

    // Elasticsearch functions
    es_execute: elasticsearch.es_execute,
    setNewObject: elasticsearch.setNewObject,
    updateObjectByID: elasticsearch.updateObjectByID,
    getObjectById: elasticsearch.getObjectById,
    getObjectWithValue: elasticsearch.getObjectWithValue,
    deleteObjectByID: elasticsearch.deleteObjectByID,
    search: elasticsearch.search,
    searchByType: elasticsearch.searchByType,
    countDocuments: elasticsearch.countDocuments,
    bulkOperations: elasticsearch.bulkOperations,
    existsDocument: elasticsearch.existsDocument,
    getEsIndex: elasticsearch.getEsIndex,
    getEsIndexLog: elasticsearch.getEsIndexLog,
    getEsIndexSessions: elasticsearch.getEsIndexSessions
};
