import { NextRequest } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";
import { RecordingService } from "@/lib/services/recording.service";
import { ApiResponseHandler } from "@/lib/utils/api-response";
import { AuthenticationError } from "@/lib/errors/app-error";

export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      throw new AuthenticationError();
    }

    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get("page") || "1");
    const limit = parseInt(searchParams.get("limit") || "20");
    const skip = (page - 1) * limit;

    const recordings = await RecordingService.getRecordingsByUserId(
      session.user.id,
      {
        skip,
        take: limit,
        orderBy: { createdAt: "desc" },
      }
    );

    // 转换日期格式以匹配前端期望的类型
    const formattedRecordings = recordings.map((recording) => ({
      ...recording,
      createdAt: recording.createdAt.toISOString(),
    }));

    return ApiResponseHandler.success(formattedRecordings);
  } catch (error) {
    return ApiResponseHandler.error(error as Error);
  }
}
