import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
import { ErrorSchema } from '@/server/utils/errorHandler';
import { AuthContext } from '@/server/types/context';
import { authMiddleware } from '@/server/middleware/auth.middleware';
import * as process from 'node:process';
import * as crypto from 'node:crypto';
import * as querystring from 'node:querystring';

// 环境变量配置
const VOD_SECRET_ID = process.env.VOD_SECRET_ID || '';
const VOD_SECRET_KEY = process.env.VOD_SECRET_KEY || '';

// 响应Schema定义
const VodSignatureResponse = z.object({
  signature: z.string().openapi({
    description: 'VOD签名',
    example: 'eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eA=='
  })
});

/**
 * 生成VOD签名
 * @param secretId VOD密钥ID
 * @param secretKey VOD密钥
 * @returns VOD签名字符串
 */
function generateVodSignature(secretId: string, secretKey: string): string {
  // 确定签名的当前时间和失效时间
  const current = Math.floor(Date.now() / 1000);
  const expired = current + 86400; // 签名有效期：1天

  // 向参数列表填入参数
  const arg_list = {
    secretId,
    currentTimeStamp: current,
    expireTime: expired,
    random: Math.round(Math.random() * Math.pow(2, 32)),
  };

  // 计算签名
  const orignal = querystring.stringify(arg_list);
  const orignal_buffer = Buffer.from(orignal, 'utf8');

  const hmac = crypto.createHmac('sha1', secretKey);
  const hmac_buffer = hmac.update(orignal_buffer).digest();

  const signature = Buffer.concat([hmac_buffer, orignal_buffer]).toString('base64');

  return signature;
}

// VOD签名生成路由定义
const vodSignatureRoute = createRoute({
  method: 'get',
  path: '/signature',
  middleware: [authMiddleware],
  responses: {
    200: {
      description: '成功生成VOD签名',
      content: { 'application/json': { schema: VodSignatureResponse } }
    },
    401: {
      description: '未授权',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 创建API应用实例
const app = new OpenAPIHono<AuthContext>()
  .openapi(vodSignatureRoute, async (c) => {
    try {
      // 检查环境变量配置
      if (!VOD_SECRET_ID || !VOD_SECRET_KEY) {
        return c.json({
          code: 500,
          message: 'VOD服务配置不完整，请检查VOD_SECRET_ID和VOD_SECRET_KEY环境变量'
        }, 500);
      }

      // 生成VOD签名
      const signature = generateVodSignature(VOD_SECRET_ID, VOD_SECRET_KEY);

      return c.json({
        signature
      }, 200);
    } catch (error) {
      console.error('VOD签名生成错误:', error);
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : 'VOD签名生成失败'
      }, 500);
    }
  });

export default app;