const dotenv = require('dotenv');

// Load environment variables
dotenv.config();

const config = {
  // Server configuration
  port: process.env.PORT || 4000,
  nodeEnv: process.env.NODE_ENV || 'development',
  environment: process.env.ENVIRONMENT || 'beta',
  
  // Database configuration
  db: {
    host: process.env.DB_HOST || 'db',
    user: process.env.DB_USER || 'postgres',
    password: process.env.DB_PASSWORD || 'postgres',
    database: process.env.DB_NAME || 'ecommerce',
    port: process.env.DB_PORT || 5432
  },
  
  // Email configuration
  email: {
    host: process.env.EMAIL_HOST || 'smtp.postmarkapp.com',
    port: process.env.EMAIL_PORT || 587,
    user: process.env.EMAIL_USER || '03c638d8-4a04-9be6',
    pass: process.env.EMAIL_PASS || '03c638d8-4a04-9be6',
    reply: process.env.EMAIL_REPLY || 'noreply@2many.ca'
  },
  
  // Payment configuration
  payment: {
    stripeEnabled: process.env.STRIPE_ENABLED === 'true',
    stripePublicKey: process.env.STRIPE_PUBLIC_KEY || '',
    stripeSecretKey: process.env.STRIPE_SECRET_KEY || '',
    stripeWebhookSecret: process.env.STRIPE_WEBHOOK_SECRET || ''
  },
  
  // Shipping configuration
  shipping: {
    enabled: process.env.SHIPPING_ENABLED === 'true',
    easypostEnabled: process.env.EASYPOST_ENABLED === 'true',
    easypostApiKey: process.env.EASYPOST_API_KEY || '',
    flatRate: parseFloat(process.env.SHIPPING_FLAT_RATE || '10.00'),
    freeThreshold: parseFloat(process.env.SHIPPING_FREE_THRESHOLD || '50.00'),
    originAddress: {
      street: process.env.SHIPPING_ORIGIN_STREET || '123 Main St',
      city: process.env.SHIPPING_ORIGIN_CITY || 'Vancouver',
      state: process.env.SHIPPING_ORIGIN_STATE || 'BC',
      zip: process.env.SHIPPING_ORIGIN_ZIP || 'V6K 1V6',
      country: process.env.SHIPPING_ORIGIN_COUNTRY || 'CA'
    },
    defaultPackage: {
      length: parseFloat(process.env.SHIPPING_DEFAULT_PACKAGE_LENGTH || '15'),
      width: parseFloat(process.env.SHIPPING_DEFAULT_PACKAGE_WIDTH || '12'),
      height: parseFloat(process.env.SHIPPING_DEFAULT_PACKAGE_HEIGHT || '10'),
      unit: process.env.SHIPPING_DEFAULT_PACKAGE_UNIT || 'cm',
      weightUnit: process.env.SHIPPING_DEFAULT_WEIGHT_UNIT || 'g'
    },
    carriersAllowed: (process.env.SHIPPING_CARRIERS_ALLOWED || 'USPS,UPS,FedEx,DHL,Canada Post,Purolator').split(',')
  },
  
  // Site configuration (domain and protocol based on environment)
  site: {
    domain: process.env.ENVIRONMENT === 'prod' ? 'rocks.2many.ca' : 'localhost:3000',
    protocol: process.env.ENVIRONMENT === 'prod' ? 'https' : 'http',
    apiDomain: process.env.ENVIRONMENT === 'prod' ? 'api.rocks.2many.ca' : 'localhost:4000'
  }
};

// This function will be called after loading settings from DB
// to override config values with DB values
config.updateFromDatabase = (settings) => {
  if (!settings) return;

  // Update email settings if they exist in DB
  const emailSettings = settings.filter(s => s.category === 'email');
  if (emailSettings.length > 0) {
    const smtpHost = emailSettings.find(s => s.key === 'smtp_host');
    const smtpPort = emailSettings.find(s => s.key === 'smtp_port');
    const smtpUser = emailSettings.find(s => s.key === 'smtp_user');
    const smtpPass = emailSettings.find(s => s.key === 'smtp_password');
    const smtpReply = emailSettings.find(s => s.key === 'smtp_from_email');
    
    if (smtpHost && smtpHost.value) config.email.host = smtpHost.value;
    if (smtpPort && smtpPort.value) config.email.port = parseInt(smtpPort.value, 10);
    if (smtpUser && smtpUser.value) config.email.user = smtpUser.value;
    if (smtpPass && smtpPass.value) config.email.pass = smtpPass.value;
    if (smtpReply && smtpReply.value) config.email.reply = smtpReply.value;
  }
  
  // Update payment settings if they exist in DB
  const paymentSettings = settings.filter(s => s.category === 'payment');
  if (paymentSettings.length > 0) {
    const stripeEnabled = paymentSettings.find(s => s.key === 'stripe_enabled');
    const stripePublic = paymentSettings.find(s => s.key === 'stripe_public_key');
    const stripeSecret = paymentSettings.find(s => s.key === 'stripe_secret_key');
    const stripeWebhook = paymentSettings.find(s => s.key === 'stripe_webhook_secret');
    
    if (stripeEnabled && stripeEnabled.value) config.payment.stripeEnabled = stripeEnabled.value === 'true';
    if (stripePublic && stripePublic.value) config.payment.stripePublicKey = stripePublic.value;
    if (stripeSecret && stripeSecret.value) config.payment.stripeSecretKey = stripeSecret.value;
    if (stripeWebhook && stripeWebhook.value) config.payment.stripeWebhookSecret = stripeWebhook.value;
  }
  
  // Update shipping settings if they exist in DB
  const shippingSettings = settings.filter(s => s.category === 'shipping');
  if (shippingSettings.length > 0) {
    const shippingEnabled = shippingSettings.find(s => s.key === 'shipping_enabled');
    const easypostEnabled = shippingSettings.find(s => s.key === 'easypost_enabled');
    const easypostApiKey = shippingSettings.find(s => s.key === 'easypost_api_key');
    const flatRate = shippingSettings.find(s => s.key === 'shipping_flat_rate');
    const freeThreshold = shippingSettings.find(s => s.key === 'shipping_free_threshold');
    const originStreet = shippingSettings.find(s => s.key === 'shipping_origin_street');
    const originCity = shippingSettings.find(s => s.key === 'shipping_origin_city');
    const originState = shippingSettings.find(s => s.key === 'shipping_origin_state');
    const originZip = shippingSettings.find(s => s.key === 'shipping_origin_zip');
    const originCountry = shippingSettings.find(s => s.key === 'shipping_origin_country');
    const packageLength = shippingSettings.find(s => s.key === 'shipping_default_package_length');
    const packageWidth = shippingSettings.find(s => s.key === 'shipping_default_package_width');
    const packageHeight = shippingSettings.find(s => s.key === 'shipping_default_package_height');
    const packageUnit = shippingSettings.find(s => s.key === 'shipping_default_package_unit');
    const weightUnit = shippingSettings.find(s => s.key === 'shipping_default_weight_unit');
    const carriersAllowed = shippingSettings.find(s => s.key === 'shipping_carriers_allowed');
    
    if (shippingEnabled && shippingEnabled.value) config.shipping.enabled = shippingEnabled.value === 'true';
    if (easypostEnabled && easypostEnabled.value) config.shipping.easypostEnabled = easypostEnabled.value === 'true';
    if (easypostApiKey && easypostApiKey.value) config.shipping.easypostApiKey = easypostApiKey.value;
    if (flatRate && flatRate.value) config.shipping.flatRate = parseFloat(flatRate.value);
    if (freeThreshold && freeThreshold.value) config.shipping.freeThreshold = parseFloat(freeThreshold.value);
    
    // Update origin address
    if (originStreet && originStreet.value) config.shipping.originAddress.street = originStreet.value;
    if (originCity && originCity.value) config.shipping.originAddress.city = originCity.value;
    if (originState && originState.value) config.shipping.originAddress.state = originState.value;
    if (originZip && originZip.value) config.shipping.originAddress.zip = originZip.value;
    if (originCountry && originCountry.value) config.shipping.originAddress.country = originCountry.value;
    
    // Update default package
    if (packageLength && packageLength.value) config.shipping.defaultPackage.length = parseFloat(packageLength.value);
    if (packageWidth && packageWidth.value) config.shipping.defaultPackage.width = parseFloat(packageWidth.value);
    if (packageHeight && packageHeight.value) config.shipping.defaultPackage.height = parseFloat(packageHeight.value);
    if (packageUnit && packageUnit.value) config.shipping.defaultPackage.unit = packageUnit.value;
    if (weightUnit && weightUnit.value) config.shipping.defaultPackage.weightUnit = weightUnit.value;
    
    // Update carriers allowed
    if (carriersAllowed && carriersAllowed.value) config.shipping.carriersAllowed = carriersAllowed.value.split(',');
  }
  
  // Update site settings if they exist in DB
  const siteSettings = settings.filter(s => s.category === 'site');
  if (siteSettings.length > 0) {
    const siteDomain = siteSettings.find(s => s.key === 'site_domain');
    const siteProtocol = siteSettings.find(s => s.key === 'site_protocol');
    const siteApiDomain = siteSettings.find(s => s.key === 'site_api_domain');
    
    if (siteDomain && siteDomain.value) config.site.domain = siteDomain.value;
    if (siteProtocol && siteProtocol.value) config.site.protocol = siteProtocol.value;
    if (siteApiDomain && siteApiDomain.value) config.site.apiDomain = siteApiDomain.value;
  }
};

module.exports = config;