/**
 * 文献引用路由
 * 用于管理文档的参考文献
 */

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

const router = express.Router();

// 获取文档的所有引用
router.get('/:documentId', async (req, res, next) => {
  try {
    const { documentId } = req.params;

    // 验证文档所有权
    const document = await prisma.document.findFirst({
      where: {
        id: documentId,
        userId: req.user.id
      }
    });

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

    const references = await prisma.reference.findMany({
      where: {
        documentId,
        userId: req.user.id
      },
      orderBy: { createdAt: 'desc' }
    });

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

// 添加引用
router.post('/:documentId', async (req, res, next) => {
  try {
    const { documentId } = req.params;
    const { title, authors, doi, url, source, year, notes, metadata } = req.body;

    // 验证文档所有权
    const document = await prisma.document.findFirst({
      where: {
        id: documentId,
        userId: req.user.id
      }
    });

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

    const reference = await prisma.reference.create({
      data: {
        documentId,
        userId: req.user.id,
        title,
        authors,
        doi,
        url,
        source,
        year,
        notes,
        metadata
      }
    });

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

// 批量添加引用
router.post('/:documentId/batch', async (req, res, next) => {
  try {
    const { documentId } = req.params;
    const { references } = req.body;

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

    // 验证文档所有权
    const document = await prisma.document.findFirst({
      where: {
        id: documentId,
        userId: req.user.id
      }
    });

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

    // 批量创建
    const createdReferences = await prisma.reference.createMany({
      data: references.map(ref => ({
        documentId,
        userId: req.user.id,
        title: ref.title,
        authors: ref.authors,
        doi: ref.doi,
        url: ref.url,
        source: ref.source,
        year: ref.year,
        notes: ref.notes,
        metadata: ref.metadata
      })),
      skipDuplicates: true
    });

    res.status(201).json({
      success: true,
      count: createdReferences.count
    });
  } catch (error) {
    next(error);
  }
});

// 更新引用
router.put('/:documentId/:referenceId', async (req, res, next) => {
  try {
    const { documentId, referenceId } = req.params;

    await prisma.reference.updateMany({
      where: {
        id: referenceId,
        documentId,
        userId: req.user.id
      },
      data: req.body
    });

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

// 删除引用
router.delete('/:documentId/:referenceId', async (req, res, next) => {
  try {
    const { documentId, referenceId } = req.params;

    await prisma.reference.deleteMany({
      where: {
        id: referenceId,
        documentId,
        userId: req.user.id
      }
    });

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

// 清空文档的所有引用
router.delete('/:documentId', async (req, res, next) => {
  try {
    const { documentId } = req.params;

    await prisma.reference.deleteMany({
      where: {
        documentId,
        userId: req.user.id
      }
    });

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

export default router;