require('dotenv').config()

const config = {
  nodeEnv: process.env.NODE_ENV || 'production',
  port: parseInt(process.env.PORT, 10) || 3000,
  region: process.env.TENCENT_REGION || 'ap-guangzhou',
  db: {
    host: process.env.DB_HOST,
    port: parseInt(process.env.DB_PORT, 10) || 3306,
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME || 'jw_beauty'
  },
  cos: {
    secretId: process.env.TENCENT_SECRET_ID,
    secretKey: process.env.TENCENT_SECRET_KEY,
    bucket: process.env.COS_BUCKET || 'jw-bucket-1426323813',
    region: process.env.COS_REGION || process.env.TENCENT_REGION || 'ap-guangzhou',
    cdnDomain: process.env.COS_CDN_DOMAIN || 'tx.vsai.net.cn'
  },
  wechat: {
    appid: process.env.WECHAT_APPID,
    secret: process.env.WECHAT_SECRET
  },
  jwt: {
    secret: process.env.JWT_SECRET || 'dev-user-secret',
    adminSecret: process.env.ADMIN_JWT_SECRET || 'dev-admin-secret',
    expiresIn: '7d'
  },
  admin: {
    username: process.env.ADMIN_USERNAME || 'admin',
    password: process.env.ADMIN_PASSWORD || 'admin'
  },
  wxpay: {
    appid: process.env.WECHAT_APPID,
    mchId: process.env.WX_MCH_ID || '',
    apiV3Key: process.env.WX_MCH_API_V3_KEY || '',
    mchSerialNo: process.env.WX_MCH_SERIAL_NO || '',
    privateKey: process.env.WX_MCH_PRIVATE_KEY || '',
    privateKeyPath: process.env.WX_MCH_PRIVATE_KEY_PATH || '',
    notifyUrl: process.env.WX_PAY_NOTIFY_URL || ''
  }
}

if (config.nodeEnv === 'production') {
  if (config.jwt.secret === 'dev-user-secret') throw new Error('JWT_SECRET must be set in production')
  if (config.jwt.adminSecret === 'dev-admin-secret') throw new Error('ADMIN_JWT_SECRET must be set in production')
  if (config.admin.username === 'admin' || config.admin.password === 'admin') throw new Error('ADMIN_USERNAME and ADMIN_PASSWORD must be changed from defaults in production')
  if (!config.wechat.appid) throw new Error('WECHAT_APPID must be set in production')
  const wp = config.wxpay
  if (!wp.mchId || !wp.apiV3Key || !wp.mchSerialNo || !wp.notifyUrl) throw new Error('WeChat Pay credentials (WX_MCH_ID, WX_MCH_API_V3_KEY, WX_MCH_SERIAL_NO, WX_PAY_NOTIFY_URL) must be set in production')
  if (!wp.privateKey && !wp.privateKeyPath) throw new Error('WX_MCH_PRIVATE_KEY or WX_MCH_PRIVATE_KEY_PATH must be set in production')
}

module.exports = config
