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

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

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

    // 获取用户数据
    const [userProfile, userSettings, recordings] = await Promise.all([
      UserService.getUserById(session.user.id),
      UserSettingsService.getUserSettings(session.user.id),
      RecordingService.getRecordingsByUserId(session.user.id),
    ]);

    // 构建导出数据
    const exportData = {
      user: {
        id: userProfile?.id,
        name: userProfile?.name,
        email: userProfile?.email,
        createdAt: userProfile?.createdAt,
        updatedAt: userProfile?.updatedAt,
      },
      settings: userSettings,
      recordings: recordings.map((recording) => ({
        id: recording.id,
        title: recording.title,
        audioUrl: recording.audioUrl,
        duration: recording.duration,
        fileSize: recording.fileSize,
        mimeType: recording.mimeType,
        createdAt: recording.createdAt.toISOString(),
      })),
      exportDate: new Date().toISOString(),
      version: "1.0.0",
    };

    // 返回 JSON 文件
    const response = new Response(JSON.stringify(exportData, null, 2), {
      headers: {
        "Content-Type": "application/json",
        "Content-Disposition": `attachment; filename="recorder-export-${Date.now()}.json"`,
      },
    });

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