import { authenticate, requirePermission } from '../../plugins/auth.js'
import { getCcUserById } from '../../services/cc-user.service.js'
import { UserType } from '../../constants.js'
import {
  getAnonymityConfig, setAnonymityConfig,
  getMaxCustomersPerMitra, setMaxCustomersPerMitra,
  getFreeTrialConfig, setFreeTrialConfig,
  getExtensionTimeoutConfig, setExtensionTimeoutConfig,
  getEarlyEndConfig, setEarlyEndConfig,
  getMitraPingConfig, setMitraPingConfig,
  getSensitivityConfig, setSensitivityConfig,
} 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) => {
  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)
    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 })
  })
}
