import Router from '@koa/router';
import { Context } from 'koa';
import * as PlayerService from './player.service';
import { BadRequestError } from '../../middleware/errorHandler';
import { optionalAuth } from '../../middleware/auth';

// 测试用户ID（开发环境使用）
const TEST_USER_ID = '1';

const router = new Router();

// 获取播放进度列表
router.get('/progress', optionalAuth, async (ctx: Context) => {
  // 开发环境使用测试用户ID
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const { audioId } = ctx.query as { audioId?: string };

  const records = await PlayerService.getPlayProgress(
    userId,
    audioId ? parseInt(audioId) : undefined
  );

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

// 保存播放进度
router.post('/progress', optionalAuth, async (ctx: Context) => {
  // 开发环境使用测试用户ID
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const body = ctx.request.body as {
    audioId: number;
    progress: number;
    duration: number;
  };
  const { audioId, progress, duration } = body;

  if (!audioId || typeof progress !== 'number' || typeof duration !== 'number') {
    throw new BadRequestError('参数错误');
  }

  const record = await PlayerService.savePlayProgress(userId, audioId, progress, duration);

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

// 更新播放进度 (在 DELETE 路由之前定义)
router.put('/progress/:audioId', optionalAuth, async (ctx: Context) => {
  // 开发环境使用测试用户ID
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const audioId = parseInt(ctx.params.audioId as string);
  const body = ctx.request.body as { progress: number; duration?: number };
  const { progress, duration } = body;

  if (typeof progress !== 'number') {
    throw new BadRequestError('进度参数错误');
  }

  const record = await PlayerService.updatePlayProgress(userId, audioId, progress, duration);

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

// 删除播放记录
router.delete('/progress/:audioId', optionalAuth, async (ctx: Context) => {
  // 开发环境使用测试用户ID
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const audioId = parseInt(ctx.params.audioId as string);

  await PlayerService.deletePlayRecord(userId, audioId);

  ctx.body = {
    code: 0,
    message: '删除成功',
  };
});

export default router;
