/**
 * 术语库路由
 * 使用数据库存储（而非文件系统）
 */

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

const router = express.Router();

// 获取用户的所有术语库
router.get('/', async (req, res, next) => {
  try {
    const glossaries = await prisma.glossary.findMany({
      where: { userId: req.user.id },
      orderBy: { createdAt: 'desc' }
    });

    res.json(glossaries);
  } catch (error) {
    next(error);
  }
});

// 获取单个术语库
router.get('/:id', async (req, res, next) => {
  try {
    const glossary = await prisma.glossary.findFirst({
      where: {
        id: req.params.id,
        userId: req.user.id
      }
    });

    if (!glossary) {
      return res.status(404).json({ error: 'Glossary not found' });
    }

    res.json(glossary);
  } catch (error) {
    next(error);
  }
});

// 创建术语库
router.post('/', async (req, res, next) => {
  try {
    const { name, enabled, entries } = req.body;

    if (!name) {
      return res.status(400).json({ error: 'Name is required' });
    }

    const glossary = await prisma.glossary.create({
      data: {
        userId: req.user.id,
        name,
        enabled: enabled !== undefined ? enabled : true,
        entries: entries || []
      }
    });

    res.status(201).json(glossary);
  } catch (error) {
    next(error);
  }
});

// 更新术语库
router.put('/:id', async (req, res, next) => {
  try {
    const { id } = req.params;
    const { name, enabled, entries } = req.body;

    // 构建更新数据
    const updateData = {};
    if (name !== undefined) updateData.name = name;
    if (enabled !== undefined) updateData.enabled = enabled;
    if (entries !== undefined) updateData.entries = entries;

    await prisma.glossary.updateMany({
      where: {
        id,
        userId: req.user.id
      },
      data: updateData
    });

    res.json({ success: true });
  } catch (error) {
    next(error);
  }
});

// 删除术语库
router.delete('/:id', async (req, res, next) => {
  try {
    await prisma.glossary.deleteMany({
      where: {
        id: req.params.id,
        userId: req.user.id
      }
    });

    res.json({ success: true });
  } catch (error) {
    next(error);
  }
});

// 批量更新术语库状态
router.patch('/batch/status', async (req, res, next) => {
  try {
    const { ids, enabled } = req.body;

    if (!Array.isArray(ids)) {
      return res.status(400).json({ error: 'ids must be an array' });
    }

    await prisma.glossary.updateMany({
      where: {
        id: { in: ids },
        userId: req.user.id
      },
      data: { enabled }
    });

    res.json({ success: true });
  } catch (error) {
    next(error);
  }
});

export default router;