import type { FastifyInstance } from 'fastify';

import {
  recordingIdParamSchema,
  startRecordingBodySchema,
} from '../schemas/recording.schema.js';
import {
  getRecording,
  startRecording,
  stopRecording,
} from '../services/recording.service.js';

/**
 * 录制 REST 路由（挂载在 /internal/v1 前缀下）
 *
 * - POST   /recordings           启动录制；返回 recordingId + 已绑定的 tracks
 * - DELETE /recordings/:id       停止录制；返回文件大小、时长、退出码、失败原因
 * - GET    /recordings/:id       查询正在进行中的录制状态（结束后返 404）
 *
 * 这些都是受 internalAuthPlugin 保护的内部接口，不直接暴露给客户端
 */
export async function recordingRoutes(app: FastifyInstance): Promise<void> {
  app.post('/recordings', async (request, reply) => {
    const body = startRecordingBodySchema.parse(request.body);
    const result = await startRecording({
      routerId: body.routerId,
      roomCode: body.roomCode,
      producerIds: body.producerIds,
    });
    reply.code(201);
    return result;
  });

  app.delete('/recordings/:id', async (request) => {
    const { id } = recordingIdParamSchema.parse(request.params);
    const result = await stopRecording(id);
    return result;
  });

  app.get('/recordings/:id', async (request) => {
    const { id } = recordingIdParamSchema.parse(request.params);
    return getRecording(id);
  });
}
