const express = require('express');
const crypto = require('crypto');
const prisma = require('../lib/prisma');
const { authMiddleware } = require('../lib/auth');

const router = express.Router();

// 生成 API Key
router.post('/', authMiddleware, async (req, res) => {
  try {
    const { name } = req.body;
    // 生成随机 API Key：eak_ + 32 位 hex
    const rawKey = `eak_${crypto.randomBytes(16).toString('hex')}`;
    const keyHash = crypto.createHash('sha256').update(rawKey).digest('hex');
    const keyPrefix = rawKey.slice(0, 12); // eak_xxxxxxxx

    const apiKey = await prisma.apiKey.create({
      data: {
        userId: req.userId,
        name: name || 'default',
        keyHash,
        keyPrefix,
      },
      select: {
        id: true,
        name: true,
        keyPrefix: true,
        createdAt: true,
      },
    });

    // 明文 Key 只返回一次
    res.json({ apiKey: { ...apiKey, key: rawKey } });
  } catch (err) {
    console.error('生成 API Key 失败:', err);
    res.status(500).json({ error: '生成失败' });
  }
});

// 列出当前用户的所有 API Key
router.get('/', authMiddleware, async (req, res) => {
  try {
    const keys = await prisma.apiKey.findMany({
      where: { userId: req.userId },
      select: {
        id: true,
        name: true,
        keyPrefix: true,
        lastUsedAt: true,
        createdAt: true,
      },
      orderBy: { createdAt: 'desc' },
    });
    res.json({ apiKeys: keys });
  } catch (err) {
    console.error('获取 API Key 列表失败:', err);
    res.status(500).json({ error: '获取失败' });
  }
});

// 删除 API Key
router.delete('/:id', authMiddleware, async (req, res) => {
  try {
    const existing = await prisma.apiKey.findUnique({
      where: { id: req.params.id },
    });
    if (!existing || existing.userId !== req.userId) {
      return res.status(404).json({ error: 'API Key 不存在' });
    }
    await prisma.apiKey.delete({ where: { id: req.params.id } });
    res.json({ deleted: true });
  } catch (err) {
    console.error('删除 API Key 失败:', err);
    res.status(500).json({ error: '删除失败' });
  }
});

module.exports = router;
