import { authenticate, requirePermission } from '../../plugins/auth.js'
import { getCcUserById } from '../../services/cc-user.service.js'
import { UserType, ExtensionTimeoutAction, SessionMode } from '../../constants.js'
import { publish } from '../../plugins/valkey.js'
import { getDb } from '../../db/client.js'
import {
  getAnonymityConfig, setAnonymityConfig,
  getMaxCustomersPerMitra, setMaxCustomersPerMitra,
  getFreeTrialConfig, setFreeTrialConfig,
  getExtensionTimeoutConfig, setExtensionTimeoutConfig,
  getEarlyEndConfig, setEarlyEndConfig,
  getMitraPingConfig, setMitraPingConfig, getMitraHeartbeatCadenceSeconds,
  getSensitivityConfig, setSensitivityConfig,
  getPaymentRequestTimeoutMinutes, setPaymentRequestTimeoutMinutes,
  getReturningChatConfirmationTimeoutSeconds, setReturningChatConfirmationTimeoutSeconds,
  getExtensionDefaultActionOnTimeout, setExtensionDefaultActionOnTimeout,
  getPairingBlastTimeoutSeconds, setPairingBlastTimeoutSeconds,
  getSupportHandles, setSupportHandles,
} from '../../services/config.service.js'

const sql = getDb()

// RFC 4122 UUID format (any variant). Loose check is fine — Postgres will reject
// malformed UUIDs at query time, but rejecting early gives a clean 422 instead.
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i

const validation = (message, field) => ({
  success: false,
  error: { code: 'VALIDATION', message, ...(field ? { field } : {}) },
})

const staleWrite = (serverUpdatedAt) => ({
  success: false,
  error: {
    code: 'STALE_WRITE',
    message: 'Pricing tier was updated by someone else. Reload and try again.',
    server_updated_at: serverUpdatedAt,
  },
})

const notFound = (message = 'Not found') => ({
  success: false,
  error: { code: 'NOT_FOUND', message },
})

// `updated_at` from a GET response may arrive as an ISO-8601 string or a JS Date.
// Compare on the underlying millisecond value to dodge millisecond-precision drift
// from string round-tripping through PG's timestamptz <-> postgres.js Date.
const updatedAtMatches = (a, b) => {
  if (!a || !b) return false
  const aMs = a instanceof Date ? a.getTime() : new Date(a).getTime()
  const bMs = b instanceof Date ? b.getTime() : new Date(b).getTime()
  return Number.isFinite(aMs) && Number.isFinite(bMs) && aMs === bMs
}

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, stale_after_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 (stale_after_seconds !== undefined) {
      const cadence = getMitraHeartbeatCadenceSeconds()
      if (typeof stale_after_seconds !== 'number' || stale_after_seconds < cadence) {
        return reply.code(422).send({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: `stale_after_seconds must be a number >= heartbeat cadence (${cadence}s)`,
          },
        })
      }
    }
    const config = await setMitraPingConfig({ require_ping, stale_after_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 getPaymentRequestTimeoutMinutes() })
  })

  app.patch('/payment-session-timeout', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { payment_request_timeout_minutes } = request.body ?? {}
    if (typeof payment_request_timeout_minutes !== 'number' || payment_request_timeout_minutes < 1) {
      return reply.code(422).send({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: 'payment_request_timeout_minutes must be a number >= 1' },
      })
    }
    const config = await setPaymentRequestTimeoutMinutes(payment_request_timeout_minutes)
    await publishConfigInvalidate('payment_request_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 / Stage 3 (relational pricing): per-row CRUD with optimistic-lock ---
  //
  // Pricing tiers and the first-session discount promotion now live in dedicated
  // relational tables (pricing_tiers / pricing_promotions). The old full-replace
  // PATCH /:mode handler is gone — every write here goes through per-row CRUD with
  // an updated_at optimistic-lock token. History rows are written in the same
  // transaction as the live-row mutation so audit can't drift from reality.
  //
  // Channel names on publishConfigInvalidate are preserved (pricing_chat_tiers_json /
  // pricing_call_tiers_json / first_session_discount) so any in-process cache
  // subscribers keep working without rewires.

  /**
   * Snapshot a tier row into pricing_tiers_history. Called inside the same
   * transaction as the live-row write so audit can't drift from reality.
   */
  const writeTierHistory = async (tx, row, { changedBy, changeKind }) => {
    await tx`
      INSERT INTO pricing_tiers_history (
        tier_id, mode, minutes, price_idr, original_price_idr, tag,
        sort_order, is_active, changed_by, change_kind
      ) VALUES (
        ${row.id}, ${row.mode}, ${row.minutes}, ${row.price_idr},
        ${row.original_price_idr ?? null}, ${row.tag ?? null},
        ${row.sort_order}, ${row.is_active},
        ${changedBy ?? null}, ${changeKind}
      )
    `
  }

  const writePromotionHistory = async (tx, row, { changedBy, changeKind }) => {
    await tx`
      INSERT INTO pricing_promotions_history (
        promotion_id, enabled, eligibility, actual_price_idr, gimmick_price_idr,
        duration_minutes, modes, starts_at, ends_at, changed_by, change_kind
      ) VALUES (
        ${row.id}, ${row.enabled}, ${row.eligibility}, ${row.actual_price_idr},
        ${row.gimmick_price_idr ?? null}, ${row.duration_minutes}, ${row.modes},
        ${row.starts_at ?? null}, ${row.ends_at ?? null},
        ${changedBy ?? null}, ${changeKind}
      )
    `
  }

  // --- Pricing tiers ---

  app.get('/pricing-tiers', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (_req, reply) => {
    const rows = await sql`
      SELECT id, mode, minutes, price_idr, original_price_idr, tag,
             sort_order, is_active, created_at, updated_at
      FROM pricing_tiers
      ORDER BY mode ASC, sort_order ASC, minutes ASC
    `
    const data = { chat: [], call: [] }
    for (const r of rows) {
      if (r.mode === SessionMode.CHAT) data.chat.push(r)
      else if (r.mode === SessionMode.CALL) data.call.push(r)
    }
    return reply.send({ success: true, data })
  })

  app.post('/pricing-tiers', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const body = request.body ?? {}
    const { mode, minutes, price_idr, original_price_idr, tag, sort_order } = body

    if (mode !== SessionMode.CHAT && mode !== SessionMode.CALL) {
      return reply.code(422).send(validation('mode must be "chat" or "call"', 'mode'))
    }
    if (typeof minutes !== 'number' || !Number.isInteger(minutes) || minutes <= 0) {
      return reply.code(422).send(validation('minutes must be a positive integer', 'minutes'))
    }
    if (typeof price_idr !== 'number' || !Number.isInteger(price_idr) || price_idr < 0) {
      return reply.code(422).send(validation('price_idr must be a non-negative integer', 'price_idr'))
    }
    if (original_price_idr !== undefined && original_price_idr !== null) {
      if (typeof original_price_idr !== 'number' || !Number.isInteger(original_price_idr) || original_price_idr < price_idr) {
        return reply.code(422).send(validation('original_price_idr must be an integer >= price_idr', 'original_price_idr'))
      }
    }
    if (tag !== undefined && tag !== null && typeof tag !== 'string') {
      return reply.code(422).send(validation('tag must be a string or null', 'tag'))
    }
    if (sort_order !== undefined && (typeof sort_order !== 'number' || !Number.isInteger(sort_order))) {
      return reply.code(422).send(validation('sort_order must be an integer', 'sort_order'))
    }

    // Pre-check uniqueness so we can return a friendly 422 instead of a 23505 leak.
    const [dup] = await sql`
      SELECT id FROM pricing_tiers WHERE mode = ${mode} AND minutes = ${minutes}
    `
    if (dup) {
      return reply.code(422).send(validation(`A tier already exists for ${mode}/${minutes}min`, 'minutes'))
    }

    let inserted
    try {
      inserted = await sql.begin(async (tx) => {
        const [row] = await tx`
          INSERT INTO pricing_tiers (mode, minutes, price_idr, original_price_idr, tag, sort_order)
          VALUES (
            ${mode}, ${minutes}, ${price_idr},
            ${original_price_idr ?? null},
            ${tag ?? null},
            ${sort_order ?? 0}
          )
          RETURNING id, mode, minutes, price_idr, original_price_idr, tag,
                    sort_order, is_active, created_at, updated_at
        `
        await writeTierHistory(tx, row, { changedBy: request.auth.userId, changeKind: 'create' })
        return row
      })
    } catch (err) {
      // 23505 = unique_violation (the (mode, minutes) constraint). Race with another writer.
      if (err.code === '23505') {
        return reply.code(422).send(validation(`A tier already exists for ${mode}/${minutes}min`, 'minutes'))
      }
      throw err
    }

    await publishConfigInvalidate(`pricing_${mode}_tiers_json`)
    return reply.code(201).send({ success: true, data: inserted })
  })

  app.patch('/pricing-tiers/:id', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { id } = request.params
    if (!UUID_RE.test(id)) {
      return reply.code(422).send(validation('id must be a UUID', 'id'))
    }

    const body = request.body ?? {}
    const { updated_at: clientUpdatedAt, price_idr, original_price_idr, tag, sort_order, is_active } = body

    if (!clientUpdatedAt) {
      return reply.code(422).send(validation('updated_at is required (optimistic-lock token)', 'updated_at'))
    }

    // Build patch object — only include fields the caller actually sent.
    const patch = {}
    if (price_idr !== undefined) {
      if (typeof price_idr !== 'number' || !Number.isInteger(price_idr) || price_idr < 0) {
        return reply.code(422).send(validation('price_idr must be a non-negative integer', 'price_idr'))
      }
      patch.price_idr = price_idr
    }
    if (original_price_idr !== undefined) {
      if (original_price_idr !== null && (typeof original_price_idr !== 'number' || !Number.isInteger(original_price_idr) || original_price_idr < 0)) {
        return reply.code(422).send(validation('original_price_idr must be a non-negative integer or null', 'original_price_idr'))
      }
      patch.original_price_idr = original_price_idr
    }
    if (tag !== undefined) {
      if (tag !== null && typeof tag !== 'string') {
        return reply.code(422).send(validation('tag must be a string or null', 'tag'))
      }
      patch.tag = tag
    }
    if (sort_order !== undefined) {
      if (typeof sort_order !== 'number' || !Number.isInteger(sort_order)) {
        return reply.code(422).send(validation('sort_order must be an integer', 'sort_order'))
      }
      patch.sort_order = sort_order
    }
    if (is_active !== undefined) {
      if (typeof is_active !== 'boolean') {
        return reply.code(422).send(validation('is_active must be a boolean', 'is_active'))
      }
      patch.is_active = is_active
    }

    const [existing] = await sql`
      SELECT id, mode, minutes, price_idr, original_price_idr, tag,
             sort_order, is_active, updated_at
      FROM pricing_tiers WHERE id = ${id}
    `
    if (!existing) {
      return reply.code(404).send(notFound('Pricing tier not found'))
    }
    if (!updatedAtMatches(clientUpdatedAt, existing.updated_at)) {
      return reply.code(409).send(staleWrite(existing.updated_at))
    }

    // Cross-field check: post-patch original_price_idr >= post-patch price_idr.
    const nextPrice = patch.price_idr ?? existing.price_idr
    const nextOrig = patch.original_price_idr === undefined ? existing.original_price_idr : patch.original_price_idr
    if (nextOrig !== null && nextOrig < nextPrice) {
      return reply.code(422).send(validation('original_price_idr must be >= price_idr', 'original_price_idr'))
    }

    const updated = await sql.begin(async (tx) => {
      // Re-check inside the transaction with FOR UPDATE so a concurrent writer's
      // commit between our pre-check and our UPDATE bumps the timestamp and we
      // catch it. Without this, two stale-with-same-token PATCHes could both win.
      const [locked] = await tx`
        SELECT id, updated_at FROM pricing_tiers WHERE id = ${id} FOR UPDATE
      `
      if (!locked) return { _notFound: true }
      if (!updatedAtMatches(clientUpdatedAt, locked.updated_at)) {
        return { _stale: locked.updated_at }
      }

      const [row] = await tx`
        UPDATE pricing_tiers
        SET price_idr          = ${patch.price_idr ?? existing.price_idr},
            original_price_idr = ${patch.original_price_idr === undefined ? existing.original_price_idr : patch.original_price_idr},
            tag                = ${patch.tag === undefined ? existing.tag : patch.tag},
            sort_order         = ${patch.sort_order ?? existing.sort_order},
            is_active          = ${patch.is_active ?? existing.is_active},
            updated_at         = NOW()
        WHERE id = ${id}
        RETURNING id, mode, minutes, price_idr, original_price_idr, tag,
                  sort_order, is_active, created_at, updated_at
      `
      await writeTierHistory(tx, row, { changedBy: request.auth.userId, changeKind: 'update' })
      return row
    })

    if (updated._notFound) return reply.code(404).send(notFound('Pricing tier not found'))
    if (updated._stale) return reply.code(409).send(staleWrite(updated._stale))

    await publishConfigInvalidate(`pricing_${updated.mode}_tiers_json`)
    return reply.send({ success: true, data: updated })
  })

  app.delete('/pricing-tiers/:id', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const { id } = request.params
    if (!UUID_RE.test(id)) {
      return reply.code(422).send(validation('id must be a UUID', 'id'))
    }

    // updated_at is the optimistic-lock token even for DELETE — same contract as PATCH.
    const clientUpdatedAt = (request.body ?? {}).updated_at
    if (!clientUpdatedAt) {
      return reply.code(422).send(validation('updated_at is required (optimistic-lock token)', 'updated_at'))
    }

    const [existing] = await sql`
      SELECT id, mode, updated_at FROM pricing_tiers WHERE id = ${id}
    `
    if (!existing) return reply.code(404).send(notFound('Pricing tier not found'))
    if (!updatedAtMatches(clientUpdatedAt, existing.updated_at)) {
      return reply.code(409).send(staleWrite(existing.updated_at))
    }

    const result = await sql.begin(async (tx) => {
      const [locked] = await tx`
        SELECT id, updated_at FROM pricing_tiers WHERE id = ${id} FOR UPDATE
      `
      if (!locked) return { _notFound: true }
      if (!updatedAtMatches(clientUpdatedAt, locked.updated_at)) {
        return { _stale: locked.updated_at }
      }

      const [row] = await tx`
        UPDATE pricing_tiers
        SET is_active = false, updated_at = NOW()
        WHERE id = ${id}
        RETURNING id, mode, minutes, price_idr, original_price_idr, tag,
                  sort_order, is_active, created_at, updated_at
      `
      await writeTierHistory(tx, row, { changedBy: request.auth.userId, changeKind: 'delete' })
      return row
    })

    if (result._notFound) return reply.code(404).send(notFound('Pricing tier not found'))
    if (result._stale) return reply.code(409).send(staleWrite(result._stale))

    await publishConfigInvalidate(`pricing_${result.mode}_tiers_json`)
    return reply.send({ success: true, data: result })
  })

  // --- First-session discount (single promotion row, eligibility='first_session') ---

  app.get('/first-session-discount', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
  }, async (_req, reply) => {
    const [row] = await sql`
      SELECT id, enabled, eligibility, actual_price_idr, gimmick_price_idr,
             duration_minutes, modes, starts_at, ends_at, created_at, updated_at
      FROM pricing_promotions
      WHERE eligibility = 'first_session'
    `
    if (!row) return reply.code(404).send(notFound('First-session discount not configured'))
    return reply.send({ success: true, data: row })
  })

  app.patch('/first-session-discount', {
    preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
  }, async (request, reply) => {
    const body = request.body ?? {}
    const {
      updated_at: clientUpdatedAt,
      enabled,
      actual_price_idr,
      gimmick_price_idr,
      duration_minutes,
      modes,
    } = body

    if (!clientUpdatedAt) {
      return reply.code(422).send(validation('updated_at is required (optimistic-lock token)', 'updated_at'))
    }

    const patch = {}
    if (enabled !== undefined) {
      if (typeof enabled !== 'boolean') {
        return reply.code(422).send(validation('enabled must be a boolean', 'enabled'))
      }
      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 (value === null && field === 'gimmick_price_idr') {
          patch[field] = null
          continue
        }
        if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
          return reply.code(422).send(validation(`${field} must be a non-negative number`, field))
        }
        if (field === 'duration_minutes' && value <= 0) {
          return reply.code(422).send(validation('duration_minutes must be > 0', field))
        }
        patch[field] = Math.round(value)
      }
    }
    if (modes !== undefined) {
      if (
        !Array.isArray(modes)
        || modes.length === 0
        || modes.some((m) => m !== SessionMode.CHAT && m !== SessionMode.CALL)
      ) {
        return reply.code(422).send(validation('modes must be a non-empty array of "chat" | "call"', 'modes'))
      }
      patch.modes = modes
    }

    const [existing] = await sql`
      SELECT id, enabled, eligibility, actual_price_idr, gimmick_price_idr,
             duration_minutes, modes, starts_at, ends_at, updated_at
      FROM pricing_promotions WHERE eligibility = 'first_session'
    `
    if (!existing) return reply.code(404).send(notFound('First-session discount not configured'))
    if (!updatedAtMatches(clientUpdatedAt, existing.updated_at)) {
      return reply.code(409).send(staleWrite(existing.updated_at))
    }

    // Cross-field: gimmick_price_idr (if set) must be >= actual_price_idr.
    const nextActual = patch.actual_price_idr ?? existing.actual_price_idr
    const nextGimmick = patch.gimmick_price_idr === undefined ? existing.gimmick_price_idr : patch.gimmick_price_idr
    if (nextGimmick !== null && nextGimmick < nextActual) {
      return reply.code(422).send(validation('gimmick_price_idr must be >= actual_price_idr', 'gimmick_price_idr'))
    }

    const updated = await sql.begin(async (tx) => {
      const [locked] = await tx`
        SELECT id, updated_at FROM pricing_promotions WHERE id = ${existing.id} FOR UPDATE
      `
      if (!locked) return { _notFound: true }
      if (!updatedAtMatches(clientUpdatedAt, locked.updated_at)) {
        return { _stale: locked.updated_at }
      }

      const [row] = await tx`
        UPDATE pricing_promotions
        SET enabled           = ${patch.enabled ?? existing.enabled},
            actual_price_idr  = ${patch.actual_price_idr ?? existing.actual_price_idr},
            gimmick_price_idr = ${patch.gimmick_price_idr === undefined ? existing.gimmick_price_idr : patch.gimmick_price_idr},
            duration_minutes  = ${patch.duration_minutes ?? existing.duration_minutes},
            modes             = ${patch.modes ?? existing.modes},
            updated_at        = NOW()
        WHERE id = ${existing.id}
        RETURNING id, enabled, eligibility, actual_price_idr, gimmick_price_idr,
                  duration_minutes, modes, starts_at, ends_at, created_at, updated_at
      `
      await writePromotionHistory(tx, row, { changedBy: request.auth.userId, changeKind: 'update' })
      return row
    })

    if (updated._notFound) return reply.code(404).send(notFound('First-session discount not configured'))
    if (updated._stale) return reply.code(409).send(staleWrite(updated._stale))

    await publishConfigInvalidate('first_session_discount')
    return reply.send({ success: true, data: updated })
  })

  // --- 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 })
  })
}
