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

const router = Router()

// ============================================================
// IoT设备 (T-310~313)
// ============================================================

router.get('/iot/devices', async (req: AuthRequest, res) => {
  try {
    const storeCode = req.query.store_code as string
    const where = storeCode ? `WHERE store_code = $1` : ''
    const params = storeCode ? [storeCode] : []
    const result = await query(`SELECT * FROM analytics.v3_iot_device ${where} ORDER BY updated_at DESC`, params)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/iot/devices', async (req: AuthRequest, res) => {
  try {
    const { device_code, device_name, device_type, store_code, location } = req.body
    const result = await query(`INSERT INTO analytics.v3_iot_device (device_code, device_name, device_type, store_code, location) VALUES ($1,$2,$3,$4,$5) ON CONFLICT (device_code) DO UPDATE SET device_name=EXCLUDED.device_name, store_code=EXCLUDED.store_code, updated_at=NOW() RETURNING *`,
      [device_code, device_name, device_type, store_code, location])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/iot/reading', async (req: AuthRequest, res) => {
  try {
    const { device_code, store_code, temperature, humidity } = req.body
    const isAlarm = (temperature !== undefined && (Number(temperature) < -5 || Number(temperature) > 10)) || (humidity !== undefined && (Number(humidity) > 80))
    const result = await query(`INSERT INTO analytics.v3_iot_temperature (device_code, store_code, temperature, humidity, recorded_at, is_alarm) VALUES ($1,$2,$3,$4,NOW(),$5) RETURNING *`,
      [device_code, store_code, temperature, humidity, isAlarm])
    await query(`UPDATE analytics.v3_iot_device SET last_reading = $1, last_reading_at = NOW(), status = $2 WHERE device_code = $3`,
      [JSON.stringify({ temperature, humidity }), isAlarm ? 'alarm' : 'online', device_code])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

router.get('/iot/temperature-history', async (req: AuthRequest, res) => {
  try {
    const deviceCode = req.query.device_code as string
    const hours = parseInt(req.query.hours as string) || 24
    const result = await query(`SELECT * FROM analytics.v3_iot_temperature WHERE device_code = $1 AND recorded_at >= NOW() - interval '${hours} hours' ORDER BY recorded_at DESC LIMIT 500`, [deviceCode])
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// AI辅助决策 (T-320~323)
// ============================================================

router.post('/ai/adjust-target', async (req: AuthRequest, res) => {
  try {
    const { target_date, store_code, original_target, factors } = req.body
    let adjustment = 1.0
    if (factors) {
      if (factors.weather === 'rain') adjustment *= 0.9
      if (factors.weather === 'sunny') adjustment *= 1.05
      if (factors.is_holiday) adjustment *= 1.15
      if (factors.is_weekend) adjustment *= 1.1
      if (factors.competitor_activity) adjustment *= 0.95
    }
    const adjustedTarget = Math.round(Number(original_target) * adjustment)
    const confidence = Math.round(adjustment * 80 * 100) / 100
    const result = await query(`INSERT INTO analytics.v3_ai_target_adjustment (target_date, store_code, original_target, adjusted_target, factors, confidence) VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (target_date, store_code) DO UPDATE SET original_target=EXCLUDED.original_target, adjusted_target=EXCLUDED.adjusted_target, factors=EXCLUDED.factors, confidence=EXCLUDED.confidence RETURNING *`,
      [target_date, store_code, original_target, adjustedTarget, JSON.stringify(factors || {}), confidence])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

router.get('/ai/forecasts', async (req: AuthRequest, res) => {
  try {
    const forecastType = req.query.type as string || 'revenue'
    const storeCode = req.query.store_code as string
    const conditions = [`forecast_type = $1`]
    const params: any[] = [forecastType]
    if (storeCode) { conditions.push(`store_code = $2`); params.push(storeCode) }
    const result = await query(`SELECT * FROM analytics.v3_forecast WHERE ${conditions.join(' AND ')} ORDER BY target_date DESC LIMIT 50`, params)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/ai/forecast', async (req: AuthRequest, res) => {
  try {
    const { forecast_type, target_date, store_code, predicted_value, confidence_lower, confidence_upper, model_type } = req.body
    const result = await query(`INSERT INTO analytics.v3_forecast (forecast_type, target_date, store_code, predicted_value, confidence_lower, confidence_upper, model_type) VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`,
      [forecast_type, target_date, store_code, predicted_value, confidence_lower, confidence_upper, model_type || 'linear'])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

// T-323: 季度战略复盘
router.post('/ai/quarterly-report', async (req: AuthRequest, res) => {
  try {
    const { quarter, year } = req.body
    const q = quarter || Math.ceil((new Date().getMonth() + 1) / 3)
    const y = year || new Date().getFullYear()
    const result = await query(`SELECT store_code, store_name, SUM(received_total) AS quarterly_revenue FROM analytics.fact_bill WHERE EXTRACT(QUARTER FROM business_date) = $1 AND EXTRACT(YEAR FROM business_date) = $2 GROUP BY store_code, store_name ORDER BY quarterly_revenue DESC`, [q, y])
    const report = { quarter: `Q${q} ${y}`, stores: result.rows, total_revenue: result.rows.reduce((s: number, r: any) => s + Number(r.quarterly_revenue || 0), 0) }
    sendSuccess(res, report)
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// 全链路自动流转 (T-330~332)
// ============================================================

router.get('/chain/production-sales', async (req: AuthRequest, res) => {
  try {
    const result = await query(`SELECT sku_code, dish_name AS sku_name, SUM(sales_quantity) AS total_sales FROM analytics.fact_bill_item WHERE ordered_at >= date_trunc('month', NOW()) GROUP BY sku_code, dish_name ORDER BY total_sales DESC LIMIT 50`)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/chain/mrp', async (req: AuthRequest, res) => {
  try {
    const { target_date, store_code } = req.body
    const salesResult = await query(`SELECT sku_code, dish_name AS sku_name, SUM(sales_quantity) AS avg_daily_sales FROM analytics.fact_bill_item WHERE ordered_at >= NOW() - interval '30 days' GROUP BY sku_code, dish_name ORDER BY avg_daily_sales DESC LIMIT 50`)
    const mrpPlan = salesResult.rows.map((r: any) => ({ ...r, recommended_production: Math.ceil(Number(r.avg_daily_sales) * 1.1) }))
    sendSuccess(res, { target_date, store_code, plan: mrpPlan })
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// 实时数据流 (T-340~341)
// ============================================================

router.get('/realtime/dashboard', async (req: AuthRequest, res) => {
  try {
    const storeCode = req.query.store_code as string
    const today = new Date().toISOString().slice(0, 10)
    const conditions = [`business_date = $1`]
    const params: any[] = [today]
    if (storeCode) { conditions.push(`store_code = $2`); params.push(storeCode) }
    const result = await query(`SELECT store_code, SUM(received_total) AS today_revenue, count(*) AS bill_count, AVG(received_total) AS avg_transaction FROM analytics.fact_bill WHERE ${conditions.join(' AND ')} GROUP BY store_code ORDER BY today_revenue DESC`, params)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// 战略驾驶舱 (T-350~352)
// ============================================================

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

router.post('/strategy/roi/calculate', async (req: AuthRequest, res) => {
  try {
    const { store_code, store_name, initial_investment, monthly_revenue, monthly_profit } = req.body
    const paybackMonths = monthly_profit > 0 ? Math.round(Number(initial_investment) / Number(monthly_profit) * 100) / 100 : null
    const roiPct = initial_investment > 0 ? Math.round(Number(monthly_profit) * 12 / Number(initial_investment) * 100 * 100) / 100 : 0
    const result = await query(`INSERT INTO analytics.v3_store_roi (store_code, store_name, initial_investment, monthly_revenue, monthly_profit, payback_months, roi_pct) VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT (store_code) DO UPDATE SET initial_investment=EXCLUDED.initial_investment, monthly_revenue=EXCLUDED.monthly_revenue, monthly_profit=EXCLUDED.monthly_profit, payback_months=EXCLUDED.payback_months, roi_pct=EXCLUDED.roi_pct, updated_at=NOW() RETURNING *`,
      [store_code, store_name, initial_investment, monthly_revenue, monthly_profit, paybackMonths, roiPct])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

router.get('/strategy/brand-assets', async (req: AuthRequest, res) => {
  try {
    const result = await query(`SELECT * FROM analytics.v3_brand_asset ORDER BY tracking_date DESC LIMIT 30`)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/strategy/brand-assets', async (req: AuthRequest, res) => {
  try {
    const { tracking_date, nps_score, search_index, sentiment_health, positive_mentions, negative_mentions } = req.body
    const result = await query(`INSERT INTO analytics.v3_brand_asset (tracking_date, nps_score, search_index, sentiment_health, positive_mentions, negative_mentions) VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (tracking_date) DO UPDATE SET nps_score=EXCLUDED.nps_score, search_index=EXCLUDED.search_index, sentiment_health=EXCLUDED.sentiment_health, positive_mentions=EXCLUDED.positive_mentions, negative_mentions=EXCLUDED.negative_mentions RETURNING *`,
      [tracking_date, nps_score, search_index, sentiment_health, positive_mentions, negative_mentions])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

// T-360: 培训锁定
router.post('/training/lock-scheduling', async (req: AuthRequest, res) => {
  try {
    const { employee_name } = req.body
    const result = await query(`SELECT * FROM analytics.v3_learning_record WHERE employee_name = $1 AND completion_status != '已完成'`, [employee_name])
    const locked = result.rows.length > 0
    sendSuccess(res, { employee_name, locked, pending_courses: result.rows.length, courses: result.rows })
  } catch (err: any) { sendError(res, err.message) }
})

export default router
