import { Router } from 'express'
import { query } from '../config/database.js'
import { sendSuccess, sendError, parsePagination } from '../middleware/error.js'
import type { AuthRequest } from '../middleware/auth.js'

const router = Router()

// ============================================================
// 预警规则管理 (T-130)
// ============================================================

router.get('/rules', async (req: AuthRequest, res) => {
  try {
    const result = await query(
      `SELECT * FROM analytics.v3_alert_rule ORDER BY id`
    )
    sendSuccess(res, result.rows)
  } catch (err: any) {
    sendError(res, err.message)
  }
})

router.post('/rules', async (req: AuthRequest, res) => {
  try {
    const { rule_name, description, metric, operator, threshold, severity, push_targets, escalation_path, check_interval, is_enabled } = req.body
    const result = await query(`
      INSERT INTO analytics.v3_alert_rule (rule_name, description, metric, operator, threshold, severity, push_targets, escalation_path, check_interval, is_enabled)
      VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
      RETURNING *
    `, [rule_name, description, metric, operator || '<', threshold, severity || 'yellow', push_targets, escalation_path, check_interval || 'hourly', is_enabled !== false])
    sendSuccess(res, result.rows[0])
  } catch (err: any) {
    sendError(res, err.message)
  }
})

router.patch('/rules/:id', async (req: AuthRequest, res) => {
  try {
    const { rule_name, description, metric, operator, threshold, severity, push_targets, escalation_path, check_interval, is_enabled } = req.body
    const updates: string[] = []
    const params: any[] = []
    let idx = 1

    if (rule_name !== undefined) { updates.push(`rule_name = $${idx++}`); params.push(rule_name) }
    if (description !== undefined) { updates.push(`description = $${idx++}`); params.push(description) }
    if (metric !== undefined) { updates.push(`metric = $${idx++}`); params.push(metric) }
    if (operator !== undefined) { updates.push(`operator = $${idx++}`); params.push(operator) }
    if (threshold !== undefined) { updates.push(`threshold = $${idx++}`); params.push(threshold) }
    if (severity !== undefined) { updates.push(`severity = $${idx++}`); params.push(severity) }
    if (push_targets !== undefined) { updates.push(`push_targets = $${idx++}`); params.push(push_targets) }
    if (escalation_path !== undefined) { updates.push(`escalation_path = $${idx++}`); params.push(escalation_path) }
    if (check_interval !== undefined) { updates.push(`check_interval = $${idx++}`); params.push(check_interval) }
    if (is_enabled !== undefined) { updates.push(`is_enabled = $${idx++}`); params.push(is_enabled) }
    updates.push(`updated_at = NOW()`)
    params.push(req.params.id)

    await query(
      `UPDATE analytics.v3_alert_rule SET ${updates.join(', ')} WHERE id = $${idx}`,
      params
    )
    sendSuccess(res, { updated: true })
  } catch (err: any) {
    sendError(res, err.message)
  }
})

router.delete('/rules/:id', async (req: AuthRequest, res) => {
  try {
    await query(`DELETE FROM analytics.v3_alert_rule WHERE id = $1`, [req.params.id])
    sendSuccess(res, { deleted: true })
  } catch (err: any) {
    sendError(res, err.message)
  }
})

// ============================================================
// 预警日志 (T-131)
// ============================================================

router.get('/logs', async (req: AuthRequest, res) => {
  try {
    const { page, pageSize, offset } = parsePagination(req)
    const severity = req.query.severity as string
    const handleStatus = req.query.handle_status as string
    const storeCode = req.query.store_code as string

    const conditions: string[] = []
    const params: any[] = []
    let paramIdx = 1

    if (severity) {
      conditions.push(`severity = $${paramIdx++}`)
      params.push(severity)
    }
    if (handleStatus) {
      conditions.push(`handle_status = $${paramIdx++}`)
      params.push(handleStatus)
    }
    if (storeCode) {
      conditions.push(`store_code = $${paramIdx++}`)
      params.push(storeCode)
    }

    const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
    const countResult = await query(`SELECT count(*) AS total FROM analytics.v3_alert_log ${where}`, params)
    const result = await query(
      `SELECT * FROM analytics.v3_alert_log ${where} ORDER BY triggered_at DESC LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
      [...params, pageSize, offset]
    )
    sendSuccess(res, result.rows, { total: parseInt(countResult.rows[0].total), page, page_size: pageSize })
  } catch (err: any) {
    sendError(res, err.message)
  }
})

// 处理预警
router.patch('/logs/:id', async (req: AuthRequest, res) => {
  try {
    const { handle_status, handle_comment } = req.body
    await query(`
      UPDATE analytics.v3_alert_log
      SET handle_status = $1, handle_comment = $2, handled_at = NOW()
      WHERE id = $3
    `, [handle_status, handle_comment, req.params.id])
    sendSuccess(res, { updated: true })
  } catch (err: any) {
    sendError(res, err.message)
  }
})

// 预警统计概览
router.get('/overview', async (req: AuthRequest, res) => {
  try {
    const today = new Date().toISOString().slice(0, 10)
    const result = await query(`
      SELECT
        count(*) AS total_alerts,
        count(*) FILTER (WHERE severity = 'red') AS red_alerts,
        count(*) FILTER (WHERE severity = 'yellow') AS yellow_alerts,
        count(*) FILTER (WHERE handle_status = 'pending') AS pending_alerts,
        count(*) FILTER (WHERE handle_status = 'resolved') AS resolved_alerts,
        count(*) FILTER (WHERE triggered_at::date = $1::date) AS today_alerts
      FROM analytics.v3_alert_log
      WHERE triggered_at > NOW() - INTERVAL '30 days'
    `, [today])
    sendSuccess(res, result.rows[0])
  } catch (err: any) {
    sendError(res, err.message)
  }
})

export default router
