import { createHash } from 'node:crypto'
import { DB } from '../db.js'

function hashKey(raw) {
  return createHash('sha256').update(raw).digest('hex')
}

export async function apiGateway(c, next) {
  const authHeader = c.req.header('Authorization') || ''
  const token = authHeader.replace(/^Bearer\s+/i, '').trim()

  if (!token) {
    return c.json({ error: 'missing_api_key', message: '请在 Authorization 头中提供 Bearer Token' }, 401)
  }

  const hash = hashKey(token)
  const record = await DB.prepare(
    'SELECT * FROM api_keys WHERE key_hash = ? AND status = ?'
  ).bind(hash, 'active').first()

  if (!record) {
    return c.json({ error: 'invalid_api_key', message: 'API Key 无效或已吊销' }, 401)
  }

  // 检查日限流
  const todayStart = Math.floor(new Date().setHours(0, 0, 0, 0) / 1000)
  const usage = await DB.prepare(
    'SELECT COUNT(*) as n FROM skill_invocations WHERE api_key_id = ? AND ts >= ?'
  ).bind(record.id, todayStart).first()
  const n = usage?.n || 0

  if (n >= record.daily_limit) {
    return c.json({
      error: 'rate_limit_exceeded',
      message: `日调用上限 ${record.daily_limit} 次已达到`,
      limit: record.daily_limit,
      used: n
    }, 429)
  }

  c.set('apiKey', record)
  c.set('apiUsageToday', n)
  await next()
}
