/**
 * 提示词池路由
 * 复用 server/src/routes/prompt-pool.js 的逻辑
 */

import express from 'express';
import { prisma } from '../db/client.js';

const router = express.Router();

// 限制数组大小
const MAX_PROMPTS_ARRAY_SIZE = 1000;

// 获取用户的 Prompt Pool
router.get('/', async (req, res, next) => {
  try {
    const promptPool = await prisma.promptPool.findUnique({
      where: { userId: req.user.id }
    });

    if (!promptPool) {
      // 返回默认空结构
      return res.json({
        prompts: [],
        healthConfig: null
      });
    }

    res.json({
      prompts: promptPool.prompts,
      healthConfig: promptPool.healthConfig
    });
  } catch (error) {
    next(error);
  }
});

// 更新 Prompt Pool（全量）
router.put('/', async (req, res, next) => {
  try {
    const { prompts, healthConfig } = req.body;

    // 输入验证
    if (!Array.isArray(prompts)) {
      return res.status(400).json({ error: 'prompts must be an array' });
    }

    // 限制数组大小
    if (prompts.length > MAX_PROMPTS_ARRAY_SIZE) {
      return res.status(400).json({ error: `Too many prompts (max ${MAX_PROMPTS_ARRAY_SIZE})` });
    }

    // 验证每个 prompt 的基本格式
    const validPrompts = prompts.filter(prompt => {
      return prompt && typeof prompt === 'object';
    });

    if (validPrompts.length !== prompts.length) {
      return res.status(400).json({ error: 'Some prompts have invalid format' });
    }

    const promptPool = await prisma.promptPool.upsert({
      where: { userId: req.user.id },
      update: {
        prompts: validPrompts,
        healthConfig
      },
      create: {
        userId: req.user.id,
        prompts: validPrompts,
        healthConfig
      }
    });

    res.json({
      prompts: promptPool.prompts,
      healthConfig: promptPool.healthConfig
    });
  } catch (error) {
    next(error);
  }
});

// 添加单个 Prompt
router.post('/prompts', async (req, res, next) => {
  try {
    const newPrompt = req.body;

    // 输入验证
    if (!newPrompt || typeof newPrompt !== 'object') {
      return res.status(400).json({ error: 'Prompt must be an object' });
    }

    // 获取当前 Prompt Pool
    let promptPool = await prisma.promptPool.findUnique({
      where: { userId: req.user.id }
    });

    let prompts = promptPool ? (promptPool.prompts || []) : [];

    // 限制数组大小
    if (prompts.length >= MAX_PROMPTS_ARRAY_SIZE) {
      return res.status(400).json({ error: `Maximum number of prompts reached (${MAX_PROMPTS_ARRAY_SIZE})` });
    }

    // 添加新 Prompt
    prompts.push(newPrompt);

    // 更新
    promptPool = await prisma.promptPool.upsert({
      where: { userId: req.user.id },
      update: { prompts },
      create: {
        userId: req.user.id,
        prompts
      }
    });

    res.status(201).json({
      prompts: promptPool.prompts,
      healthConfig: promptPool.healthConfig
    });
  } catch (error) {
    next(error);
  }
});

// 删除指定 Prompt（根据索引或 ID）
router.delete('/prompts/:identifier', async (req, res, next) => {
  try {
    const { identifier } = req.params;

    const promptPool = await prisma.promptPool.findUnique({
      where: { userId: req.user.id }
    });

    if (!promptPool) {
      return res.status(404).json({ error: 'Prompt pool not found' });
    }

    let prompts = promptPool.prompts || [];

    // 尝试作为索引解析
    const index = parseInt(identifier);
    if (!isNaN(index) && index >= 0 && index < prompts.length) {
      prompts.splice(index, 1);
    } else {
      // 尝试作为 ID 查找
      const initialLength = prompts.length;
      prompts = prompts.filter(p => p.id !== identifier);

      if (prompts.length === initialLength) {
        return res.status(404).json({ error: 'Prompt not found' });
      }
    }

    // 更新
    const updated = await prisma.promptPool.update({
      where: { userId: req.user.id },
      data: { prompts }
    });

    res.json({
      prompts: updated.prompts,
      healthConfig: updated.healthConfig
    });
  } catch (error) {
    next(error);
  }
});

export default router;