import express from 'express';
import { randomUUID } from 'crypto';
import cron from 'node-cron';
import { cronScheduler } from '../services/builtin-tools/cron-scheduler.js';
import { feishuDb } from '../database/db.js';

const router = express.Router();

function resolveChannelFields(channel, webhookUrl, userUuid) {
  if (channel === 'feishu') {
    const binding = feishuDb.getBindingByUserUuid(userUuid);
    if (!binding) return { error: '未绑定飞书账号', status: 400 };
    return { feishuOpenId: binding.feishu_open_id, chatId: null };
  }
  if (channel === 'webhook') {
    if (!webhookUrl) return { error: 'Webhook 渠道需要提供 URL', status: 400 };
    return { webhookUrl };
  }
  return {}; // 网页端
}

// GET /api/cron-tasks — 列出当前用户所有定时任务
router.get('/', (req, res) => {
  const userUuid = req.user.uuid;
  const tasks = cronScheduler.list(userUuid);
  res.json({ tasks });
});

// POST /api/cron-tasks — 创建定时任务
router.post('/', (req, res) => {
  const userUuid = req.user.uuid;
  const { cronExpr, prompt, recurring = true, channel = '', webhookUrl, projectPath } = req.body;

  if (!cronExpr || !prompt) {
    return res.status(400).json({ error: '缺少 cronExpr 或 prompt' });
  }
  if (!cron.validate(cronExpr)) {
    return res.status(400).json({ error: '无效的 cron 表达式' });
  }

  const channelFields = resolveChannelFields(channel, webhookUrl, userUuid);
  if (channelFields.error) {
    return res.status(channelFields.status).json({ error: channelFields.error });
  }

  try {
    const task = cronScheduler.create({
      id: randomUUID().replace(/-/g, '').slice(0, 8),
      cronExpr,
      prompt,
      recurring,
      userUuid,
      sessionId: null,
      projectPath: projectPath || null,
      sessionMode: 'new_session',
      channel,
      feishuOpenId: channelFields.feishuOpenId || null,
      chatId: channelFields.chatId || null,
      webhookUrl: channelFields.webhookUrl || null,
    });
    res.json({ task });
  } catch (e) {
    res.status(400).json({ error: e.message });
  }
});

// PUT /api/cron-tasks/:id — 编辑定时任务
router.put('/:id', (req, res) => {
  const userUuid = req.user.uuid;
  const { id } = req.params;
  const { cronExpr, prompt, recurring = true, channel = '', webhookUrl, projectPath } = req.body;

  if (!cronExpr || !prompt) {
    return res.status(400).json({ error: '缺少 cronExpr 或 prompt' });
  }
  if (!cron.validate(cronExpr)) {
    return res.status(400).json({ error: '无效的 cron 表达式' });
  }

  // 验证任务存在且属于当前用户
  const tasks = cronScheduler.list(userUuid);
  if (!tasks.find(t => t.id === id)) {
    return res.status(404).json({ error: '任务不存在或无权限' });
  }

  const channelFields = resolveChannelFields(channel, webhookUrl, userUuid);
  if (channelFields.error) {
    return res.status(channelFields.status).json({ error: channelFields.error });
  }

  const task = cronScheduler.update(id, userUuid, {
    cronExpr, prompt, recurring, channel,
    projectPath: projectPath || null,
    feishuOpenId: channelFields.feishuOpenId || null,
    chatId: channelFields.chatId || null,
    webhookUrl: channelFields.webhookUrl || null,
  });

  if (!task) return res.status(500).json({ error: '更新失败' });
  res.json({ task });
});

// DELETE /api/cron-tasks/:id — 删除定时任务
router.delete('/:id', (req, res) => {
  const userUuid = req.user.uuid;
  const { id } = req.params;
  const ok = cronScheduler.delete(id, userUuid);
  if (!ok) {
    return res.status(404).json({ error: '任务不存在或无权限' });
  }
  res.json({ success: true });
});

// PATCH /api/cron-tasks/:id/pause — 切换暂停/恢复状态
router.patch('/:id/pause', (req, res) => {
  const userUuid = req.user.uuid;
  const { id } = req.params;
  const tasks = cronScheduler.list(userUuid);
  const task = tasks.find(t => t.id === id);
  if (!task) {
    return res.status(404).json({ error: '任务不存在或无权限' });
  }
  const ok = task.isPaused
    ? cronScheduler.resume(id, userUuid)
    : cronScheduler.pause(id, userUuid);
  if (!ok) {
    return res.status(500).json({ error: '操作失败' });
  }
  res.json({ success: true, isPaused: !task.isPaused });
});

export default router;
