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()

// ============================================================
// 供应商SRM (T-201~205)
// ============================================================

router.get('/suppliers', async (req: AuthRequest, res) => {
  try {
    const grade = req.query.grade as string
    const where = grade ? `WHERE grade = $1` : ''
    const params = grade ? [grade] : []
    const result = await query(`SELECT * FROM analytics.v3_supplier_master ${where} ORDER BY overall_score DESC NULLS LAST`, params)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/suppliers', async (req: AuthRequest, res) => {
  try {
    const { supplier_code, supplier_name, category, contact_person, contact_phone, address } = req.body
    const result = await query(`
      INSERT INTO analytics.v3_supplier_master (supplier_code, supplier_name, category, contact_person, contact_phone, address)
      VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (supplier_code) DO UPDATE SET supplier_name = EXCLUDED.supplier_name, updated_at = NOW() RETURNING *
    `, [supplier_code, supplier_name, category, contact_person, contact_phone, address])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

// T-202: 供应商评分
router.post('/suppliers/:code/score', async (req: AuthRequest, res) => {
  try {
    const { delivery_on_time_rate, quality_score, price_score, service_score, food_safety_score } = req.body
    const overall = ((Number(delivery_on_time_rate) + Number(quality_score) + Number(price_score) + Number(service_score) + Number(food_safety_score)) / 5).toFixed(2)
    let grade = '合格'
    if (Number(overall) >= 90) grade = '战略'
    else if (Number(overall) >= 80) grade = '优选'
    else if (Number(overall) < 60) grade = '淘汰'
    await query(`UPDATE analytics.v3_supplier_master SET delivery_on_time_rate=$1, quality_score=$2, price_score=$3, service_score=$4, food_safety_score=$5, overall_score=$6, grade=$7, updated_at=NOW() WHERE supplier_code=$8`,
      [delivery_on_time_rate, quality_score, price_score, service_score, food_safety_score, overall, grade, req.params.code])
    sendSuccess(res, { scored: true, overall_score: overall, grade })
  } catch (err: any) { sendError(res, err.message) }
})

// T-203: 采购订单
router.get('/purchase-orders', async (req: AuthRequest, res) => {
  try {
    const status = req.query.status as string
    const where = status ? `WHERE status = $1` : ''
    const params = status ? [status] : []
    const result = await query(`SELECT * FROM analytics.v3_purchase_order ${where} ORDER BY created_at DESC LIMIT 100`, params)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/purchase-orders', async (req: AuthRequest, res) => {
  try {
    const { supplier_code, store_code, order_date, expected_delivery_date, items } = req.body
    const poNumber = `PO-${Date.now()}`
    const totalAmount = (items || []).reduce((s: number, i: any) => s + Number(i.quantity * i.unit_price || 0), 0)
    const result = await query(`INSERT INTO analytics.v3_purchase_order (po_number, supplier_code, store_code, order_date, expected_delivery_date, total_amount, created_by) VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`,
      [poNumber, supplier_code, store_code, order_date, expected_delivery_date, totalAmount, req.user?.name || 'system'])
    const poId = result.rows[0].id
    for (const item of items || []) {
      await query(`INSERT INTO analytics.v3_purchase_order_item (po_id, sku_code, sku_name, quantity, unit, unit_price, total_price) VALUES ($1,$2,$3,$4,$5,$6,$7)`,
        [poId, item.sku_code, item.sku_name, item.quantity, item.unit, item.unit_price, item.quantity * item.unit_price])
    }
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

// T-204: 比价
router.get('/price-comparison', async (req: AuthRequest, res) => {
  try {
    const skuCode = req.query.sku_code as string
    const result = await query(`
      SELECT poi.sku_code, poi.sku_name, po.supplier_code, sm.supplier_name, poi.unit_price, po.order_date
      FROM analytics.v3_purchase_order_item poi
      JOIN analytics.v3_purchase_order po ON poi.po_id = po.id
      LEFT JOIN analytics.v3_supplier_master sm ON po.supplier_code = sm.supplier_code
      WHERE poi.sku_code = $1 AND po.status IN ('delivered','settled')
      ORDER BY po.order_date DESC LIMIT 20
    `, [skuCode])
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// 审批流 (T-220~230)
// ============================================================

router.get('/approvals', async (req: AuthRequest, res) => {
  try {
    const status = req.query.status as string
    const where = status ? `WHERE status = $1` : ''
    const params = status ? [status] : []
    const result = await query(`SELECT * FROM analytics.v3_approval_request ${where} ORDER BY created_at DESC LIMIT 100`, params)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/approvals', async (req: AuthRequest, res) => {
  try {
    const { request_type, request_data } = req.body
    const rulesResult = await query(`SELECT * FROM analytics.v3_approval_rule WHERE request_type = $1 AND is_enabled = true ORDER BY step_order`, [request_type])
    const totalSteps = rulesResult.rows.length
    const result = await query(`INSERT INTO analytics.v3_approval_request (request_type, applicant_id, applicant_name, store_code, status, current_step, total_steps, request_data) VALUES ($1,$2,$3,$4,'pending',1,$5,$6) RETURNING *`,
      [request_type, String(req.user?.id || ''), req.user?.name || '', req.user?.storeCode || '', totalSteps, JSON.stringify(request_data || {})])
    const requestId = result.rows[0].id
    for (const rule of rulesResult.rows) {
      await query(`INSERT INTO analytics.v3_approval_step (request_id, step_order, approver_role, result) VALUES ($1,$2,$3,'pending')`,
        [requestId, rule.step_order, rule.approver_role])
    }
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

// T-223: 审批操作
router.post('/approvals/:id/approve', async (req: AuthRequest, res) => {
  try {
    const { result: approveResult, comment } = req.body
    const reqResult = await query(`SELECT * FROM analytics.v3_approval_request WHERE id = $1`, [req.params.id])
    if (reqResult.rows.length === 0) return sendError(res, 'Approval not found', 404)
    const approvalReq = reqResult.rows[0]
    const currentStep = approvalReq.current_step

    await query(`UPDATE analytics.v3_approval_step SET result=$1, comment=$2, approver_id=$3, approver_name=$4, approved_at=NOW() WHERE request_id=$5 AND step_order=$6`,
      [approveResult, comment || '', String(req.user?.id || ''), req.user?.name || '', req.params.id, currentStep])

    if (approveResult === 'approved') {
      const nextStep = currentStep + 1
      if (nextStep > approvalReq.total_steps) {
        await query(`UPDATE analytics.v3_approval_request SET status='approved', current_step=$1, updated_at=NOW() WHERE id=$2`, [nextStep, req.params.id])
        sendSuccess(res, { approved: true, completed: true })
      } else {
        await query(`UPDATE analytics.v3_approval_request SET current_step=$1, updated_at=NOW() WHERE id=$2`, [nextStep, req.params.id])
        sendSuccess(res, { approved: true, nextStep })
      }
    } else {
      await query(`UPDATE analytics.v3_approval_request SET status='rejected', updated_at=NOW() WHERE id=$1`, [req.params.id])
      sendSuccess(res, { rejected: true })
    }
  } catch (err: any) { sendError(res, err.message) }
})

router.get('/approvals/:id/steps', async (req: AuthRequest, res) => {
  try {
    const result = await query(`SELECT * FROM analytics.v3_approval_step WHERE request_id = $1 ORDER BY step_order`, [req.params.id])
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// 消息推送 (T-241~242)
// ============================================================

router.get('/notifications', async (req: AuthRequest, res) => {
  try {
    const userId = String(req.user?.id || '')
    const userRole = req.user?.role || ''
    const result = await query(`SELECT * FROM analytics.v3_notification WHERE user_id = $1 OR user_role = $2 ORDER BY created_at DESC LIMIT 50`, [userId, userRole])
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.patch('/notifications/:id/read', async (req: AuthRequest, res) => {
  try {
    await query(`UPDATE analytics.v3_notification SET is_read = true WHERE id = $1`, [req.params.id])
    sendSuccess(res, { read: true })
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/notifications', async (req: AuthRequest, res) => {
  try {
    const { user_id, user_role, title, content, notification_type, related_id } = req.body
    const result = await query(`INSERT INTO analytics.v3_notification (user_id, user_role, title, content, notification_type, related_id) VALUES ($1,$2,$3,$4,$5,$6) RETURNING *`,
      [user_id, user_role, title, content, notification_type, related_id])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// HR (T-250~254)
// ============================================================

router.get('/hr/attendance', async (req: AuthRequest, res) => {
  try {
    const month = (req.query.month as string) || new Date().toISOString().slice(0, 7)
    const result = await query(`
      SELECT store_code, employee_name,
        count(*) FILTER (WHERE check_in_time IS NOT NULL) AS work_days,
        count(*) FILTER (WHERE check_in_time IS NULL AND ar_date NOT IN (SELECT generate_series(d, d + interval '6 days', interval '1 day')::date FROM generate_series(date_trunc('month', $1::date)::date, date_trunc('month', $1::date)::date) d)) AS absent_days,
        avg(EXTRACT(EPOCH FROM (check_out_time - check_in_time))/3600) AS avg_hours
      FROM attendance_records
      WHERE to_char(ar_date, 'YYYY-MM') = $1
      GROUP BY store_code, employee_name
      ORDER BY store_code, employee_name
    `, [month])
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.get('/hr/talent-matrix', async (req: AuthRequest, res) => {
  try {
    const result = await query(`
      SELECT employee_name, store_code,
        performance_score, potential_score,
        CASE
          WHEN performance_score >= 80 AND potential_score >= 80 THEN 'star'
          WHEN performance_score >= 80 AND potential_score < 80 THEN 'core'
          WHEN performance_score < 80 AND potential_score >= 80 THEN 'potential'
          ELSE 'ordinary'
        END AS quadrant
      FROM (
        SELECT e.employee_name, e.store_code,
          COALESCE(ep.performance_score, 70) AS performance_score,
          COALESCE(60, 60) AS potential_score
        FROM analytics.dim_employee e
        LEFT JOIN LATERAL (
          SELECT AVG(CASE WHEN t.status = '已完成' THEN 85 ELSE 60 END) AS performance_score
          FROM analytics.store_task t WHERE t.owner = e.employee_name
        ) ep ON true
        WHERE e.status = '在职'
      ) t
      ORDER BY performance_score DESC, potential_score DESC
      LIMIT 200
    `)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// LMS (T-260~264)
// ============================================================

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

router.post('/training/courses', async (req: AuthRequest, res) => {
  try {
    const { course_name, course_type, content_url, exam_enabled, pass_score } = req.body
    const result = await query(`INSERT INTO analytics.v3_training_course (course_name, course_type, content_url, exam_enabled, pass_score) VALUES ($1,$2,$3,$4,$5) RETURNING *`,
      [course_name, course_type, content_url, exam_enabled || false, pass_score || 60])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

router.get('/training/records', async (req: AuthRequest, res) => {
  try {
    const employeeName = req.query.employee as string
    const where = employeeName ? `WHERE employee_name = $1` : ''
    const params = employeeName ? [employeeName] : []
    const result = await query(`SELECT * FROM analytics.v3_learning_record ${where} ORDER BY updated_at DESC LIMIT 100`, params)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/training/records', async (req: AuthRequest, res) => {
  try {
    const { course_id, employee_name, store_code, progress_pct, completion_status, exam_score } = req.body
    const result = await query(`INSERT INTO analytics.v3_learning_record (course_id, employee_name, store_code, progress_pct, completion_status, exam_score, started_at) VALUES ($1,$2,$3,$4,$5,$6,NOW()) RETURNING *`,
      [course_id, employee_name, store_code, progress_pct || 0, completion_status || '进行中', exam_score])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// 营销MA (T-270~273)
// ============================================================

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

router.post('/campaigns', async (req: AuthRequest, res) => {
  try {
    const { campaign_name, campaign_type, start_date, end_date, budget, target_stores } = req.body
    const result = await query(`INSERT INTO analytics.v3_marketing_campaign (campaign_name, campaign_type, start_date, end_date, budget, target_stores) VALUES ($1,$2,$3,$4,$5,$6) RETURNING *`,
      [campaign_name, campaign_type, start_date, end_date, budget, target_stores])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

router.get('/coupons', async (req: AuthRequest, res) => {
  try {
    const campaignId = req.query.campaign_id as string
    const where = campaignId ? `WHERE campaign_id = $1` : ''
    const params = campaignId ? [campaignId] : []
    const result = await query(`SELECT * FROM analytics.v3_coupon ${where} ORDER BY created_at DESC LIMIT 100`, params)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/coupons', async (req: AuthRequest, res) => {
  try {
    const { campaign_id, coupon_type, face_value, min_spend, expiry_date, count } = req.body
    const coupons = []
    for (let i = 0; i < (count || 1); i++) {
      const code = `CP-${Date.now()}-${i}`
      const result = await query(`INSERT INTO analytics.v3_coupon (campaign_id, coupon_code, coupon_type, face_value, min_spend, expiry_date) VALUES ($1,$2,$3,$4,$5,$6) RETURNING *`,
        [campaign_id, code, coupon_type, face_value, min_spend, expiry_date])
      coupons.push(result.rows[0])
    }
    sendSuccess(res, coupons)
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// 财务ERP (T-280~281)
// ============================================================

router.get('/budgets', async (req: AuthRequest, res) => {
  try {
    const year = parseInt(req.query.year as string) || new Date().getFullYear()
    const result = await query(`SELECT * FROM analytics.v3_budget WHERE year = $1 ORDER BY month, store_code`, [year])
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/budgets', async (req: AuthRequest, res) => {
  try {
    const { year, month, store_code, department, budget_type, budget_amount } = req.body
    const result = await query(`INSERT INTO analytics.v3_budget (year, month, store_code, department, budget_type, budget_amount) VALUES ($1,$2,$3,$4,$5,$6) RETURNING *`,
      [year, month, store_code, department, budget_type, budget_amount])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// 扫码确认 (T-290~292)
// ============================================================

router.post('/scan/production', async (req: AuthRequest, res) => {
  try {
    const { store_code, sku_code, batch_no, operator } = req.body
    sendSuccess(res, { scanned: true, type: 'production', store_code, sku_code, batch_no, operator, timestamp: new Date().toISOString() })
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/scan/receiving', async (req: AuthRequest, res) => {
  try {
    const { store_code, po_number, sku_code, received_qty, operator } = req.body
    if (po_number) {
      await query(`UPDATE analytics.v3_purchase_order SET status = 'delivered', actual_delivery_date = NOW() WHERE po_number = $1`, [po_number])
    }
    sendSuccess(res, { scanned: true, type: 'receiving', store_code, po_number, sku_code, received_qty, operator, timestamp: new Date().toISOString() })
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/scan/inspection', async (req: AuthRequest, res) => {
  try {
    const { store_code, inspector, score, issues } = req.body
    sendSuccess(res, { scanned: true, type: 'inspection', store_code, inspector, score, issues, timestamp: new Date().toISOString() })
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// 闭环验证 (T-295~296)
// ============================================================

router.get('/loop-verification', async (req: AuthRequest, res) => {
  try {
    const result = await query(`SELECT * FROM analytics.v3_loop_verification ORDER BY check_date DESC LIMIT 100`)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/loop-verification/check', async (req: AuthRequest, res) => {
  try {
    const { loop_name, store_code } = req.body
    const checkDate = new Date().toISOString().slice(0, 10)
    const taskResult = await query(`SELECT count(*) AS total, count(*) FILTER (WHERE status = '已完成') AS completed FROM analytics.store_task WHERE store_code = $1 AND created_at >= date_trunc('month', NOW())`, [store_code])
    const total = parseInt(taskResult.rows[0].total)
    const completed = parseInt(taskResult.rows[0].completed)
    const completionRate = total > 0 ? Math.round(completed / total * 100 * 100) / 100 : 0
    const status = completionRate >= 90 ? 'completed' : completionRate >= 50 ? 'open' : 'escalated'
    const result = await query(`INSERT INTO analytics.v3_loop_verification (loop_name, store_code, check_date, status, completion_rate) VALUES ($1,$2,$3,$4,$5) RETURNING *`,
      [loop_name, store_code, checkDate, status, completionRate])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

// ============================================================
// 安全与审计 (T-300~304)
// ============================================================

router.get('/audit-logs', async (req: AuthRequest, res) => {
  try {
    const result = await query(`SELECT * FROM analytics.v3_audit_log ORDER BY created_at DESC LIMIT 100`)
    sendSuccess(res, result.rows)
  } catch (err: any) { sendError(res, err.message) }
})

router.post('/audit-logs', async (req: AuthRequest, res) => {
  try {
    const { action, resource_type, resource_id, details } = req.body
    const result = await query(`INSERT INTO analytics.v3_audit_log (user_id, user_name, user_role, action, resource_type, resource_id, details) VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`,
      [String(req.user?.id || ''), req.user?.name || '', req.user?.role || '', action, resource_type, resource_id, JSON.stringify(details || {})])
    sendSuccess(res, result.rows[0])
  } catch (err: any) { sendError(res, err.message) }
})

// T-300: PII脱敏
router.post('/pii/mask', async (req: AuthRequest, res) => {
  try {
    const { fields } = req.body
    const masked: Record<string, string> = {}
    for (const [key, value] of Object.entries(fields)) {
      const v = String(value)
      if (v.length <= 2) masked[key] = '**'
      else if (key.includes('phone') || key.includes('mobile')) masked[key] = v.slice(0, 3) + '****' + v.slice(-4)
      else if (key.includes('id_card') || key.includes('idcard')) masked[key] = v.slice(0, 6) + '********' + v.slice(-4)
      else if (key.includes('email')) masked[key] = v.slice(0, 2) + '***@' + v.split('@')[1]
      else masked[key] = v.slice(0, 1) + '**' + v.slice(-1)
    }
    sendSuccess(res, masked)
  } catch (err: any) { sendError(res, err.message) }
})

// T-301: 匿名排名
router.get('/anonymous-ranking', async (req: AuthRequest, res) => {
  try {
    const metric = (req.query.metric as string) || 'revenue'
    const result = await query(`
      SELECT store_code, store_name, ${metric} AS metric_value,
        NTILE(10) OVER (ORDER BY ${metric} DESC) AS decile
      FROM analytics.mv_store_risk_rating_monthly
      WHERE month_start = date_trunc('month', NOW())::date
      ORDER BY ${metric} DESC
    `)
    const ranked = result.rows.map((r: any) => ({ ...r, display_rank: `TOP${r.decile}0%`, store_name: `门店${r.decile}0%区间` }))
    sendSuccess(res, ranked)
  } catch (err: any) { sendError(res, err.message) }
})

export default router
