import Router from '@koa/router';
import { Context } from 'koa';
import * as SubscriptionService from './subscription.service';
import { BadRequestError } from '../../middleware/errorHandler';
import { authMiddleware, optionalAuth } from '../../middleware/auth';
import { prisma } from '../../models';

const router = new Router();

// 获取所有套餐列表
router.get('/plans', async (ctx: Context) => {
  const plans = await SubscriptionService.getPlans();

  ctx.body = {
    code: 0,
    message: 'success',
    data: { plans }
  };
});

// 获取单个套餐详情
router.get('/plans/:id', async (ctx: Context) => {
  const planId = parseInt(ctx.params.id);
  const plan = await SubscriptionService.getPlanById(planId);

  ctx.body = {
    code: 0,
    message: 'success',
    data: { plan }
  };
});

// 获取用户订阅信息
router.get('/subscription', authMiddleware, async (ctx: Context) => {
  const userId = parseInt(ctx.state.user.userId);
  const subscription = await SubscriptionService.getUserSubscription(userId);

  ctx.body = {
    code: 0,
    message: 'success',
    data: { subscription }
  };
});

// 获取用户Token余额
router.get('/balance', authMiddleware, async (ctx: Context) => {
  const userId = parseInt(ctx.state.user.userId);
  const balance = await SubscriptionService.getUserTokenBalance(userId);

  ctx.body = {
    code: 0,
    message: 'success',
    data: balance
  };
});

// 获取Token使用记录
router.get('/usage', authMiddleware, async (ctx: Context) => {
  const userId = parseInt(ctx.state.user.userId);
  const { page = '1', pageSize = '20' } = ctx.query as { page?: string; pageSize?: string };
  
  const result = await SubscriptionService.getTokenUsageList(
    userId,
    Number(page) || 1,
    Number(pageSize) || 20
  );

  ctx.body = {
    code: 0,
    message: 'success',
    data: result
  };
});

// 获取用户配额（兼容旧接口）
router.get('/quota', authMiddleware, async (ctx: Context) => {
  const userId = parseInt(ctx.state.user.userId);
  const quota = await SubscriptionService.getUserQuota(userId);

  ctx.body = {
    code: 0,
    message: 'success',
    data: quota
  };
});

// 检查配额
router.post('/check-quota', authMiddleware, async (ctx: Context) => {
  const userId = parseInt(ctx.state.user.userId);
  const { tokens } = ctx.request.body as { tokens: number };

  if (!tokens || tokens <= 0) {
    throw new BadRequestError('请提供正确的Token数量');
  }

  const result = await SubscriptionService.checkQuota(userId, tokens);

  ctx.body = {
    code: 0,
    message: 'success',
    data: result
  };
});

// ============================================
// 书籍生成配额相关API
// ============================================

// 获取书籍规模预估字数
router.get('/book-scale-estimate', async (ctx: Context) => {
  const { scale } = ctx.query as { scale?: string };
  
  const result = SubscriptionService.estimateBookWords(scale || '1000');
  
  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      ...result,
      audioMinutes: SubscriptionService.estimateAudioMinutesFromWords(result.avg)
    }
  };
});

// 检查书籍生成配额（生成前预估）
router.get('/book-generation-quota', authMiddleware, async (ctx: Context) => {
  const userId = parseInt(ctx.state.user.userId);
  const { scale } = ctx.query as { scale?: string };
  
  if (!scale) {
    throw new BadRequestError('请提供书籍规模');
  }
  
  const result = await SubscriptionService.checkBookGenerationQuota(userId, scale);
  
  ctx.body = {
    code: 0,
    message: result.allowed ? '额度充足' : '额度不足',
    data: result
  };
});

// 检查当前额度是否足够生成指定字数（生成过程监控）
router.post('/check-quota-words', authMiddleware, async (ctx: Context) => {
  const userId = parseInt(ctx.state.user.userId);
  const { wordCount } = ctx.request.body as { wordCount: number };
  
  if (!wordCount || wordCount <= 0) {
    throw new BadRequestError('请提供正确的字数');
  }
  
  const result = await SubscriptionService.checkQuotaForWords(userId, wordCount);
  
  ctx.body = {
    code: 0,
    message: 'success',
    data: result
  };
});

// 获取用户音频时长余额（新版）
router.get('/audio-balance', authMiddleware, async (ctx: Context) => {
  const userId = parseInt(ctx.state.user.userId);
  const balance = await SubscriptionService.getUserAudioBalance(userId);
  
  ctx.body = {
    code: 0,
    message: 'success',
    data: balance
  };
});

// 获取音频生成预估
router.get('/audio-estimate', authMiddleware, async (ctx: Context) => {
  const userId = parseInt(ctx.state.user.userId);
  const { textLength } = ctx.query as { textLength?: string };
  
  if (!textLength || isNaN(parseInt(textLength))) {
    throw new BadRequestError('请提供正确的文本长度');
  }
  
  const estimate = await SubscriptionService.getAudioEstimate(userId, parseInt(textLength));
  
  ctx.body = {
    code: 0,
    message: 'success',
    data: estimate
  };
});

// ========== Token 包（按量购买） ==========

// 获取 Token 包信息
router.get('/token-packs', async (ctx: Context) => {
  const pack = SubscriptionService.TOKEN_PACK_CONFIG;
  ctx.body = {
    code: 0,
    data: {
      minutesPerPack: pack.minutesPerPack,
      unitPrice: pack.packUnitPrice,
      packPrice: pack.packPrice,
      packQuotaValue: pack.packQuotaValue,
      description: `${pack.minutesPerPack}分钟音频额度，单买¥${pack.packPrice}（月价的${pack.packPriceMultiplier}倍）`,
    },
  };
});

// 购买 Token 包
router.post('/token-packs/purchase', optionalAuth, async (ctx: Context) => {
  const userId = parseInt(String(ctx.state.user?.userId || ctx.query.userId || '1'));
  const { quantity } = (ctx.request.body || {}) as { quantity?: number };
  
  const result = await SubscriptionService.purchaseTokenPack(userId, quantity || 1);
  ctx.status = result.success ? 200 : 400;
  ctx.body = result;
});

// 购买历史
router.get('/token-packs/history', optionalAuth, async (ctx: Context) => {
  const userId = parseInt(String(ctx.state.user?.userId || ctx.query.userId || '1'));
  const history = await SubscriptionService.getTokenPackPurchases(userId);
  ctx.body = { code: 0, data: history };
});

// ========== 用户账单（AiCallLog 消耗明细） ==========

// 获取用户账单汇总
router.get('/billing/summary', optionalAuth, async (ctx: Context) => {
  const userId = ctx.state.user?.userId || ctx.query.userId || '1'; // 默认测试用户

  const logs = await prisma.aiCallLog.findMany({
    where: { userId: parseInt(userId as string) },
    orderBy: { createdAt: 'desc' },
    select: {
      id: true, callType: true, provider: true, model: true,
      userId: true, bookId: true,
      textLen: true, inputTokens: true, outputTokens: true,
      estimatedCost: true, duration: true, success: true,
      createdAt: true,
    },
  });

  // 按类型汇总
  const byType: Record<string, { count: number; inputTokens: number; outputTokens: number; cost: number }> = {};
  for (const l of logs) {
    if (!byType[l.callType]) byType[l.callType] = { count: 0, inputTokens: 0, outputTokens: 0, cost: 0 };
    byType[l.callType].count++;
    byType[l.callType].inputTokens += l.inputTokens;
    byType[l.callType].outputTokens += l.outputTokens;
    byType[l.callType].cost += l.estimatedCost || 0;
  }

  const totalCost = logs.reduce((s, l) => s + (l.estimatedCost || 0), 0);
  const balance = await SubscriptionService.getUserAudioBalance(parseInt(userId as string));
  const monthlyCost = await SubscriptionService.getUserMonthlyCost(parseInt(userId as string));

  ctx.body = {
    code: 0,
    data: {
      // 配额信息（基于 AiCallLog 真实消耗）
      quota: {
        totalMinutes: balance.totalMinutes,
        usedMinutes: balance.usedMinutes,
        remainingMinutes: balance.remainingMinutes,
        monthlyCost: Math.round(monthlyCost * 10000) / 10000,
      },
      totalCalls: logs.length,
      totalInputTokens: logs.reduce((s,l) => s + l.inputTokens, 0),
      totalOutputTokens: logs.reduce((s,l) => s + l.outputTokens, 0),
      totalCost: Math.round(totalCost * 10000) / 10000,
      byType: Object.entries(byType).map(([type, d]) => ({
        type,
        count: d.count,
        inputTokens: d.inputTokens,
        outputTokens: d.outputTokens,
        cost: Math.round(d.cost * 10000) / 10000,
      })),
      records: logs.slice(0, 50).map(l => ({
        id: l.id,
        callType: l.callType,
        provider: l.provider,
        model: l.model,
        userId: l.userId,
        bookId: l.bookId,
        textLen: l.textLen,
        inputTokens: l.inputTokens,
        outputTokens: l.outputTokens,
        cost: l.estimatedCost,
        duration: l.duration,
        success: l.success,
        time: l.createdAt,
      })),
    },
  };
});

export default router;
