import Router from '@koa/router';
import { Context } from 'koa';
import { optionalAuth } from '../../middleware/auth';
import { prisma } from '../../models';

const TEST_USER_ID = '1';

const router = new Router();

// 获取音频生成历史列表
router.get('/', optionalAuth, async (ctx: Context) => {
  // 开发环境使用测试用户ID
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const page = parseInt(ctx.query.page as string) || 1;
  const pageSize = parseInt(ctx.query.pageSize as string) || 20;
  const startDate = ctx.query.startDate as string;

  const where: any = {};
  if (startDate) {
    where.createdAt = { gte: new Date(startDate) };
  }

  const [records, total] = await Promise.all([
    prisma.audioRecord.findMany({
      where,
      orderBy: { createdAt: 'desc' },
      skip: (page - 1) * pageSize,
      take: pageSize,
    }),
    prisma.audioRecord.count({ where }),
  ]);

  const list = records.map((r) => ({
    _id: r.audioId,
    id: r.audioId,
    title: r.title,
    text: r.text || '',
    summary: '',
    tags: [],
    audioUrl: r.audioUrl || '',
    audioDuration: r.audioDuration,
    audioSize: r.audioSize,
    wordCount: r.wordCount,
    voiceId: r.voiceId,
    voiceParams: r.voiceParams ? JSON.parse(r.voiceParams) : { speed: 1, pitch: 0, volume: 50 },
    status: r.status,
    isFavorite: false,
    bookId: r.bookId,
    createdAt: r.createdAt.toISOString(),
    updatedAt: r.updatedAt.toISOString(),
  }));

  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      list,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    },
  };
});

export default router;
