import { authenticate, requirePermission } from '../../plugins/auth.js'
import { getCcUserById } from '../../services/cc-user.service.js'
import { UserType, ExtensionTimeoutAction } from '../../constants.js'
import { publish } from '../../plugins/valkey.js'
import {
  getAnonymityConfig, setAnonymityConfig,
  getMaxCustomersPerMitra, setMaxCustomersPerMitra,
  getFreeTrialConfig, setFreeTrialConfig,
  getExtensionTimeoutConfig, setExtensionTimeoutConfig,
  getEarlyEndConfig, setEarlyEndConfig,
  getMitraPingConfig, setMitraPingConfig,
  getSensitivityConfig, setSensitivityConfig,
  getPaymentSessionTimeoutMinutes, setPaymentSessionTimeoutMinutes,
  getReturningChatConfirmationTimeoutSeconds, setReturningChatConfirmationTimeoutSeconds,
  getExtensionDefaultActionOnTimeout, setExtensionDefaultActionOnTimeout,
  getPairingBlastTimeoutSeconds, setPairingBlastTimeoutSeconds,
  getFirstSessionDiscountConfig, setFirstSessionDiscountConfig,
  getSupportHandles, setSupportHandles,
  getPricingTierGroups, setPricingTierGroup,
} from '../../services/config.service.js'

const attachCcUser = async (request, reply) => {
  if (request.auth?.userType !== UserType.CC_USER) {
    return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
  }
  const user = await getCcUserById(request.auth.userId)
  if (!user) return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
  request.ccUser = user
}

export const internalConfigRoutes = async (app) => {
  // Cross-instance config invalidate. Local mutators (e.g. setMaxCustomersPerMitra) bust
  // their own in-process caches directly; this publish fans out to other instances.
  const publishConfigInvalidate = async (key) => {
    try {
      await publish('config:invalidate', { key, ts: Date.now() })
    } catch (err) {
      // Valkey may be down in dev. Local invalidate already happened.
      app.log.warn({ err, key }, 'config invalidate publish failed')
    }
  }

  app.get('/anonymity', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const config = await getAnonymityConfig()
    return reply.send({ success: true, data: config })
  })

  app.patch('/anonymity', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { anonymity_enabled } = request.body ?? {}
    if (typeof anonymity_enabled !== 'boolean') {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'anonymity_enabled must be a boolean' } })
    }
    const config = await setAnonymityConfig(anonymity_enabled)
    return reply.send({ success: true, data: config })
  })

  app.get('/max-customers-per-mitra', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const config = await getMaxCustomersPerMitra()
    return reply.send({ success: true, data: config })
  })

  app.patch('/max-customers-per-mitra', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { max_customers_per_mitra } = request.body ?? {}
    if (typeof max_customers_per_mitra !== 'number' || max_customers_per_mitra < 1) {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'max_customers_per_mitra must be a positive number' } })
    }
    const config = await setMaxCustomersPerMitra(max_customers_per_mitra)
    await publishConfigInvalidate('max_customers_per_mitra')
    return reply.send({ success: true, data: config })
  })

  // --- Phase 3: Free Trial ---
  app.get('/free-trial', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const config = await getFreeTrialConfig()
    return reply.send({ success: true, data: config })
  })

  app.patch('/free-trial', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { enabled, duration_minutes } = request.body ?? {}
    const config = await setFreeTrialConfig({ enabled, duration_minutes })
    return reply.send({ success: true, data: config })
  })

  // --- Phase 3: Extension Timeout ---
  app.get('/extension-timeout', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const config = await getExtensionTimeoutConfig()
    return reply.send({ success: true, data: config })
  })

  app.patch('/extension-timeout', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { extension_timeout_seconds } = request.body ?? {}
    if (typeof extension_timeout_seconds !== 'number' || extension_timeout_seconds < 10) {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'Must be a number >= 10' } })
    }
    const config = await setExtensionTimeoutConfig(extension_timeout_seconds)
    return reply.send({ success: true, data: config })
  })

  // --- Phase 3: Early End ---
  app.get('/early-end', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const config = await getEarlyEndConfig()
    return reply.send({ success: true, data: config })
  })

  app.patch('/early-end', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { mitra_enabled, customer_enabled } = request.body ?? {}
    const config = await setEarlyEndConfig({ mitra_enabled, customer_enabled })
    return reply.send({ success: true, data: config })
  })

  // --- Phase 3.1: Mitra Ping Config ---
  app.get('/mitra-ping', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const config = await getMitraPingConfig()
    return reply.send({ success: true, data: config })
  })

  app.patch('/mitra-ping', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { require_ping, ping_interval_seconds } = request.body ?? {}
    if (require_ping !== undefined && typeof require_ping !== 'boolean') {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'require_ping must be a boolean' } })
    }
    if (ping_interval_seconds !== undefined && (typeof ping_interval_seconds !== 'number' || ping_interval_seconds < 5)) {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'ping_interval_seconds must be a number >= 5' } })
    }
    const config = await setMitraPingConfig({ require_ping, ping_interval_seconds })
    return reply.send({ success: true, data: config })
  })

  // --- Phase 3.3: Topic Sensitivity ---
  app.get('/sensitivity', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const config = await getSensitivityConfig()
    return reply.send({ success: true, data: config })
  })

  app.patch('/sensitivity', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { flip_confirmation_enabled, one_way_latch } = request.body ?? {}
    if (flip_confirmation_enabled !== undefined && typeof flip_confirmation_enabled !== 'boolean') {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'flip_confirmation_enabled must be a boolean' } })
    }
    if (one_way_latch !== undefined && typeof one_way_latch !== 'boolean') {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'one_way_latch must be a boolean' } })
    }
    const config = await setSensitivityConfig({ flip_confirmation_enabled, one_way_latch })
    return reply.send({ success: true, data: config })
  })

  // --- Price Tiers ---
  app.get('/price-tiers', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (request, reply) => {
    const { getPriceTiers } = await import('../../services/pricing.service.js')
    const tiers = await getPriceTiers()
    return reply.send({ success: true, data: tiers })
  })

  app.patch('/price-tiers', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { tiers } = request.body ?? {}
    if (!Array.isArray(tiers) || tiers.length === 0) {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'tiers must be a non-empty array' } })
    }
    for (const t of tiers) {
      if (!t.duration_minutes || t.price === undefined || !t.label) {
        return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'Each tier needs duration_minutes, price, and label' } })
      }
    }
    const { getDb } = await import('../../db/client.js')
    const sql = getDb()
    await sql`UPDATE app_config SET value = ${sql.json({ tiers })}, updated_at = NOW() WHERE key = 'price_tiers'`
    return reply.send({ success: true, data: tiers })
  })

  // --- Paid pairing flow + extension flip ---

  app.get('/payment-session-timeout', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (_req, reply) => {
    return reply.send({ success: true, data: await getPaymentSessionTimeoutMinutes() })
  })

  app.patch('/payment-session-timeout', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { payment_session_timeout_minutes } = request.body ?? {}
    if (typeof payment_session_timeout_minutes !== 'number' || payment_session_timeout_minutes < 1) {
      return reply.code(422).send({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: 'payment_session_timeout_minutes must be a number >= 1' },
      })
    }
    const config = await setPaymentSessionTimeoutMinutes(payment_session_timeout_minutes)
    await publishConfigInvalidate('payment_session_timeout_minutes')
    return reply.send({ success: true, data: config })
  })

  app.get('/returning-chat-timeout', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (_req, reply) => {
    return reply.send({ success: true, data: await getReturningChatConfirmationTimeoutSeconds() })
  })

  app.patch('/returning-chat-timeout', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { returning_chat_confirmation_timeout_seconds } = request.body ?? {}
    if (typeof returning_chat_confirmation_timeout_seconds !== 'number' || returning_chat_confirmation_timeout_seconds < 5) {
      return reply.code(422).send({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: 'returning_chat_confirmation_timeout_seconds must be a number >= 5' },
      })
    }
    const config = await setReturningChatConfirmationTimeoutSeconds(returning_chat_confirmation_timeout_seconds)
    await publishConfigInvalidate('returning_chat_confirmation_timeout_seconds')
    return reply.send({ success: true, data: config })
  })

  app.get('/extension-default-action', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (_req, reply) => {
    return reply.send({ success: true, data: await getExtensionDefaultActionOnTimeout() })
  })

  app.patch('/extension-default-action', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { extension_default_action_on_timeout } = request.body ?? {}
    if (!Object.values(ExtensionTimeoutAction).includes(extension_default_action_on_timeout)) {
      return reply.code(422).send({
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: `extension_default_action_on_timeout must be one of: ${Object.values(ExtensionTimeoutAction).join(', ')}`,
        },
      })
    }
    const config = await setExtensionDefaultActionOnTimeout(extension_default_action_on_timeout)
    await publishConfigInvalidate('extension_default_action_on_timeout')
    return reply.send({ success: true, data: config })
  })

  app.get('/pairing-blast-timeout', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (_req, reply) => {
    return reply.send({ success: true, data: await getPairingBlastTimeoutSeconds() })
  })

  app.patch('/pairing-blast-timeout', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { pairing_blast_timeout_seconds } = request.body ?? {}
    if (typeof pairing_blast_timeout_seconds !== 'number' || pairing_blast_timeout_seconds < 5) {
      return reply.code(422).send({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: 'pairing_blast_timeout_seconds must be a number >= 5' },
      })
    }
    const config = await setPairingBlastTimeoutSeconds(pairing_blast_timeout_seconds)
    await publishConfigInvalidate('pairing_blast_timeout_seconds')
    return reply.send({ success: true, data: config })
  })

  // --- Phase 4: First-session discount ---
  app.get('/first-session-discount', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (_req, reply) => {
    return reply.send({ success: true, data: await getFirstSessionDiscountConfig() })
  })

  app.patch('/first-session-discount', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { enabled, actual_price_idr, gimmick_price_idr, duration_minutes, modes } = request.body ?? {}
    const patch = {}
    if (enabled !== undefined) {
      if (typeof enabled !== 'boolean') {
        return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'enabled must be a boolean' } })
      }
      patch.enabled = enabled
    }
    for (const [field, value] of [
      ['actual_price_idr', actual_price_idr],
      ['gimmick_price_idr', gimmick_price_idr],
      ['duration_minutes', duration_minutes],
    ]) {
      if (value !== undefined) {
        if (typeof value !== 'number' || value < 0 || !Number.isFinite(value)) {
          return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: `${field} must be a non-negative number` } })
        }
        patch[field] = Math.round(value)
      }
    }
    if (modes !== undefined) {
      if (!Array.isArray(modes) || modes.some((m) => m !== 'chat' && m !== 'call')) {
        return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'modes must be an array of "chat" | "call"' } })
      }
      patch.modes = modes
    }
    const config = await setFirstSessionDiscountConfig(patch)
    await publishConfigInvalidate('first_session_discount')
    return reply.send({ success: true, data: config })
  })

  // --- Phase 4: Pricing tier groups (chat / call) ---
  app.get('/pricing-tiers', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (_req, reply) => {
    return reply.send({ success: true, data: await getPricingTierGroups() })
  })

  app.patch('/pricing-tiers/:mode', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const mode = request.params.mode
    if (mode !== 'chat' && mode !== 'call') {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'mode must be chat or call' } })
    }
    const { tiers } = request.body ?? {}
    if (!Array.isArray(tiers) || tiers.length === 0) {
      return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'tiers must be a non-empty array' } })
    }
    for (const t of tiers) {
      if (
        typeof t.id !== 'string'
        || typeof t.minutes !== 'number' || t.minutes <= 0
        || typeof t.price_idr !== 'number' || t.price_idr < 0
      ) {
        return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'each tier needs id (string), minutes (number > 0), price_idr (number >= 0)' } })
      }
    }
    const config = await setPricingTierGroup(mode, tiers)
    await publishConfigInvalidate(`pricing_${mode}_tiers_json`)
    return reply.send({ success: true, data: config })
  })

  // --- Phase 4: Support handles ---
  app.get('/support-handles', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (_req, reply) => {
    return reply.send({ success: true, data: await getSupportHandles() })
  })

  app.patch('/support-handles', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { wa, telegram } = request.body ?? {}
    const validateHandle = (h, name) => {
      if (h === undefined) return null
      if (typeof h !== 'object' || h === null) return `${name} must be an object`
      if (h.label !== undefined && typeof h.label !== 'string') return `${name}.label must be a string`
      if (h.deeplink !== undefined && typeof h.deeplink !== 'string') return `${name}.deeplink must be a string`
      return null
    }
    for (const [name, value] of [['wa', wa], ['telegram', telegram]]) {
      const err = validateHandle(value, name)
      if (err) return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: err } })
    }
    const config = await setSupportHandles({ wa, telegram })
    await publishConfigInvalidate('support_handles_json')
    return reply.send({ success: true, data: config })
  })
}
