import dotenv from 'dotenv';
dotenv.config();

const env = process.env;

const domain = env.DOMAIN ?? 'localhost:3000';
const isLocal = domain.startsWith('localhost') || domain.startsWith('127.');
const origin = env.ORIGIN ?? (isLocal ? `http://${domain}` : `https://${domain}`);

const sinsayGoogleMapsKey = 'AIzaSyBd_a_c8FDJE4HVnxbgh4FbwSUrnztHG9c';
const mirrorGoogleMapsKey = String(env.GOOGLE_MAPS_API_KEY ?? '').trim();

export const config = {
  isLocal,
  port: parseInt(env.PORT ?? '3000', 10),
  domain,
  origin,

  /**
   * Google Maps on checkout/store locator.
   * Sinsay key only works when the page URL is www.sinsay.com.
   * Set GOOGLE_MAPS_API_KEY (Maps JavaScript API) with your domain in HTTP referrers.
   */
  googleMaps: {
    sinsayKey: sinsayGoogleMapsKey,
    mirrorKey: mirrorGoogleMapsKey,
    effectiveKey: mirrorGoogleMapsKey || sinsayGoogleMapsKey,
    useMirrorKey: Boolean(mirrorGoogleMapsKey),
  },

  upstream: {
    main: 'https://www.sinsay.com',
    media: 'https://media.sinsay.com',
    static: 'https://static.sinsay.com',
    fastend: 'https://fastend.sinsay.com',
  },

  /** URL prefix on OUR domain that maps to media.sinsay.com */
  cdnPrefix: '/_cdn/media',
  staticCdnPrefix: '/_cdn/static',

  /**
   * Cart/checkout intercept config.
   *
   * Verified against www.sinsay.com/pl/pl on 2026-05-18:
   * - Add-to-cart opens a minicart modal, then cart page uses gRPC-web:
   *   POST https://fastend.sinsay.com/cart_hamster.cart.CartService/Get
   * - Product/cart JS bundles define these gRPC-web methods:
   *   AddProduct, Get, ChangeProductQty, RemoveProduct, RemoveCart,
   *   RemoveByProductId, RemoveByQuoteId, AddCoupon, RemoveCoupon.
   * - Cart page: /pl/pl/checkout/cart/
   * - Checkout order target: /pl/pl/checkout/order/ (logged-out users redirect to
   *   /pl/pl/customer/account/login/referer/<base64-checkout-order>/)
   */
  intercept: {
    cartPathPrefixes: [
      '/api/basket',
      '/api/v1/basket',
      '/api/v2/basket',
      '/api/cart',
    ],
    cartGrpcMethods: {
      get: '/cart_hamster.cart.CartService/Get',
      addProduct: '/cart_hamster.cart.CartService/AddProduct',
      changeProductQty: '/cart_hamster.cart.CartService/ChangeProductQty',
      removeProduct: '/cart_hamster.cart.CartService/RemoveProduct',
      removeCart: '/cart_hamster.cart.CartService/RemoveCart',
      removeByProductId: '/cart_hamster.cart.CartService/RemoveByProductId',
      removeByQuoteId: '/cart_hamster.cart.CartService/RemoveByQuoteId',
      addCoupon: '/cart_hamster.cart.CartService/AddCoupon',
      removeCoupon: '/cart_hamster.cart.CartService/RemoveCoupon',
    },
    cartPagePath: '/pl/pl/checkout/cart/',
    checkoutOrderPath: '/pl/pl/checkout/order/',
    /** Official Sinsay “thank you” SPA route (proxied HTML, same as www.sinsay.com). */
    checkoutOrderCreatedPath: '/pl/pl/checkout/order/created/',
    auroraWebhookPath: '/api/aurora/webhook',
    checkoutOrderErrorPath: '/pl/pl/checkout/order/error/',
    checkoutLoginRedirectPrefix: '/pl/pl/customer/account/login/referer/',
    checkoutPath: '/checkout',
    orderApiPath: '/api/our/order',
    pingPath: '/__proxy/ping',
    /** Cookiebot declaration proxy (cookies-list page) */
    cookieDeclarationPath: '/__proxy/cookie-declaration',
    /** Google Maps referer proxy (store locator) */
    googleMapsProxyPrefix: '/__proxy/google',
    googleMapsBridgePath: '/__proxy/google-maps-bridge.js',
    googleMapsSwPath: '/__proxy/google-maps-sw.js',
    /** Luigi/Luma search AI integration proxy */
    luigisboxProxyPrefix: '/__proxy/luigisbox',
    /** Official wishlist API proxy used after login */
    wishlistApiProxyPrefix: '/__proxy/wishlist-api',
    /** Zowie live chat widget proxy */
    zowieProxyPrefix: '/__proxy/zowie',
    /** Sinsay product JSON API (sizes, variants) */
    archProxyPrefix: '/__proxy/arch',
    /** Support chat API (Telegram bridge) */
    supportApiPrefix: '/api/support',
    checkoutSessionPath: '/api/checkout/session',
    checkoutCatalogPath: '/api/checkout/catalog',
    sinsayAjxProxyPrefix: '/pl/pl/ajx',
  },

  bot: {
    apiKey: env.BOT_API_KEY ?? '',
  },

  checkout: {
    draftTtlSec: 60 * 60 * 24,
    draftCookieName: 'checkout_sid',
    /** When true, POST .../pay creates Felopay token and returns redirectUrl */
    payEnabled: env.CHECKOUT_PAY_ENABLED === 'true',
  },

  support: {
    enabled: env.SUPPORT_ENABLED !== 'false',
    zowieInstanceId: env.ZOWIE_INSTANCE_ID ?? '5d15b4a5b5a140bdb9b6b6f5c5bc4338',
    zowieChatbotId: env.ZOWIE_CHATBOT_ID ?? 'b0e3bd02db464b0ca37accc27adc3578',
    zowieUpstream: env.ZOWIE_UPSTREAM ?? 'https://eu1.chat.getzowie.com',
    welcomeMessage:
      env.SUPPORT_WELCOME_MESSAGE ??
      'Cześć 👋 Jestem wirtualnym asystentem Sinsay! Masz pytanie? Chętnie Ci pomogę 😉\n\nAbym mógł udzielić Ci dokładnej odpowiedzi, proszę zadaj pytanie w jednej wiadomości, opisując dokładnie, czego dotyczy Twoje zapytanie.\n\nCześć! 👋 Jak mogę Ci dzisiaj pomóc? 😊',
  },

  session: {
    secret: env.SESSION_SECRET ?? 'dev-secret-please-change-me',
    cookieName: 'sid',
    visitorCookieName: 'vid',
    visitorMaxAge: 60 * 60 * 24 * 365,
  },

  admin: {
    user: env.ADMIN_USER ?? 'admin',
    pass: env.ADMIN_PASS ?? 'changeme',
    path: '/_admin',
  },

  tg: {
    token: env.TG_BOT_TOKEN ?? '',
    adminChatIds: (env.TG_ADMIN_CHAT_ID ?? '')
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean),
  },

  /** Telegram bot + channel for live chat support (Zowie bridge). */
  supportTg: {
    token: env.SUPPORT_TG_BOT_TOKEN ?? '',
    chatIds: (env.SUPPORT_TG_CHAT_ID ?? '')
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean),
  },

  /**
   * Separate Telegram channel for mirror-side operational events.
   * Distinct token and chat from `tg.*` so the gateway's manager bot is unaffected.
   */
  mirrorTg: {
    token: env.MIRROR_TELEGRAM_BOT_TOKEN ?? '',
    chatId: env.MIRROR_TELEGRAM_CHAT_ID ?? '',
  },

  geoip: {
    provider: (env.GEOIP_PROVIDER ?? 'ip-api') as 'ip-api' | 'ipinfo' | 'none',
    token: env.IPINFO_TOKEN ?? '',
    timeoutMs: parseInt(env.GEOIP_TIMEOUT_MS ?? '2500', 10),
  },

  proxyPool: {
    enabled: env.PROXY_POOL_ENABLED === 'true',
    urls: (env.PROXY_POOL_URLS ?? '').split(',').filter(Boolean),
  },

  redis: {
    url: env.REDIS_URL ?? 'redis://localhost:6379',
  },

  aurora: {
    apiBase: env.AURORA_API_BASE ?? 'http://sinsay-payment:4177',
    apiKey: env.AURORA_MERCHANT_API_KEY ?? '',
    webhookSecret: env.AURORA_WEBHOOK_SECRET ?? '',
    merchantId: env.AURORA_MERCHANT_ID ?? 'sinsay',
    webhookUrl: env.AURORA_WEBHOOK_URL ?? `${origin}/api/aurora/webhook`,
  },

  payment: {
    felopayRedirectBase: env.FELOPAY_REDIRECT_BASE ?? 'https://felopay.com/',
    apiSecret: env.FELOPAY_API_SECRET ?? '6cadf140641315c7b2aa6272d58824b5baaaf8b58f067fdf60a4975d77dc2cb4',
    tokenBytes: 24,
    states: {
      new:       { id: 1, label: 'Nowe' },
      processing:{ id: 3, label: 'W trakcie realizacji' },
      paid:      { id: 2, label: 'Opłacone' },
      failed:    { id: 8, label: 'Błąd płatności' },
      cancelled: { id: 6, label: 'Anulowane' },
    } as Record<string, { id: number; label: string }>,
    currencies: { PLN: 2, EUR: 1, USD: 3 } as Record<string, number>,
  },

  /** Online visitor window in seconds (used by /online Telegram command) */
  onlineWindowSec: 300,

  /**
   * Global price adjustment for the mirror catalog/cart.
   * PRICE_DISCOUNT_PERCENT=40 → all prices are 40% lower (×0.6).
   * 0 = disabled (upstream prices unchanged).
   */
  pricing: {
    discountPercent: Math.min(
      99,
      Math.max(0, parseFloat(env.PRICE_DISCOUNT_PERCENT ?? '0') || 0),
    ),
  },

  /** Customer support phone shown above WhatsApp on help/contacts pages. */
  contact: {
    phoneDisplay: env.CONTACT_PHONE ?? '+48 884 742 071',
    phoneTel: env.CONTACT_PHONE_TEL ?? '+48884742071',
    whatsappDigits: env.CONTACT_WHATSAPP ?? '48884742071',
  },

  analytics: {
    enabled: env.ANALYTICS_ENABLED !== 'false',
    ipSalt: env.ANALYTICS_IP_SALT ?? env.SESSION_SECRET ?? 'dev-secret-please-change-me',
    adminUser: env.ANALYTICS_ADMIN_USER ?? 'admin',
    adminPassword: env.ANALYTICS_ADMIN_PASSWORD ?? 'adminpass228',
    sessionSecret: env.ANALYTICS_SESSION_SECRET ?? env.SESSION_SECRET ?? 'dev-secret-please-change-me',
    sessionCookie: 'analytics_session',
    csrfCookie: 'analytics_csrf',
    sessionCookieName: 'asid',
    collectRateLimit: parseInt(env.ANALYTICS_COLLECT_RATE_LIMIT ?? '120', 10),
    loginRateLimit: parseInt(env.ANALYTICS_LOGIN_RATE_LIMIT ?? '10', 10),
    onlineWindowSec: parseInt(env.ANALYTICS_ONLINE_WINDOW_SEC ?? '90', 10),
    sessionTtlSec: 60 * 30,
    adminSessionTtlSec: 60 * 60 * 24 * 7,
    timezone: 'Europe/Warsaw',
    dashboardPath: '/analytics',
    collectPath: '/api/analytics/collect',
    apiPrefix: '/api/analytics',
  },
} as const;

export type Config = typeof config;
