import Router from '@koa/router';
import { audioEditService } from './audioedit.service';

const router = new Router();

/**
 * 裁剪音频
 * POST /api/audio/trim
 */
router.post('/trim', async (ctx) => {
  try {
    const { audioId, startTime, endTime } = ctx.request.body as {
      audioId: string;
      startTime: number;
      endTime: number;
    };

    if (!audioId || startTime === undefined || endTime === undefined) {
      ctx.body = {
        code: 400,
        message: '缺少必填字段',
      };
      return;
    }

    if (startTime >= endTime) {
      ctx.body = {
        code: 400,
        message: '起始时间必须小于结束时间',
      };
      return;
    }

    const result = await audioEditService.trimAudio(audioId, startTime, endTime);
    ctx.body = {
      code: 0,
      message: 'success',
      data: result,
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '裁剪失败',
    };
  }
});

/**
 * 合并音频
 * POST /api/audio/merge
 */
router.post('/merge', async (ctx) => {
  try {
    const { audioIds, order } = ctx.request.body as {
      audioIds: string[];
      order?: number[];
    };

    if (!audioIds || audioIds.length < 2) {
      ctx.body = {
        code: 400,
        message: '至少需要两个音频才能合并',
      };
      return;
    }

    const mergeOrder = order || audioIds.map((_, i) => i);
    const result = await audioEditService.mergeAudios(audioIds, mergeOrder);
    ctx.body = {
      code: 0,
      message: 'success',
      data: result,
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '合并失败',
    };
  }
});

/**
 * 获取音频信息
 * GET /api/audio/:audioId/info
 */
router.get('/:audioId/info', async (ctx) => {
  try {
    const { audioId } = ctx.params;
    const result = await audioEditService.getAudioInfo(audioId);
    ctx.body = {
      code: 0,
      message: 'success',
      data: result,
    };
  } catch (error: any) {
    ctx.body = {
      code: 400,
      message: error.message || '获取音频信息失败',
    };
  }
});

export default router;