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

const router = Router()

// 获取所有调度任务
router.get('/', async (req: AuthRequest, res) => {
  try {
    const result = await query(
      `SELECT * FROM analytics.v3_scheduled_task ORDER BY id`
    )
    sendSuccess(res, result.rows)
  } catch (err: any) {
    sendError(res, err.message)
  }
})

// 更新调度任务（启停 / 修改 cron）
router.patch('/:id', async (req: AuthRequest, res) => {
  try {
    const { is_enabled, cron_expr, description } = req.body
    const updates: string[] = []
    const params: any[] = []
    let idx = 1

    if (is_enabled !== undefined) {
      updates.push(`is_enabled = $${idx++}`)
      params.push(is_enabled)
    }
    if (cron_expr) {
      updates.push(`cron_expr = $${idx++}`)
      params.push(cron_expr)
    }
    if (description !== undefined) {
      updates.push(`description = $${idx++}`)
      params.push(description)
    }
    updates.push(`updated_at = NOW()`)
    params.push(req.params.id)

    await query(
      `UPDATE analytics.v3_scheduled_task SET ${updates.join(', ')} WHERE id = $${idx}`,
      params
    )

    await reloadScheduler()
    sendSuccess(res, { updated: true })
  } catch (err: any) {
    sendError(res, err.message)
  }
})

// 手动触发调度任务
router.post('/:id/trigger', async (req: AuthRequest, res) => {
  try {
    const result = await query(
      `SELECT task_name FROM analytics.v3_scheduled_task WHERE id = $1`, [req.params.id]
    )
    if (result.rows.length === 0) {
      return sendError(res, 'Task not found', 404)
    }
    await triggerTaskManually(result.rows[0].task_name)
    sendSuccess(res, { triggered: true })
  } catch (err: any) {
    sendError(res, err.message)
  }
})

export default router
