import { NextRequest } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";
import { RecordingService } from "@/lib/services/recording.service";
import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3";

const s3 = new S3Client({
  region: process.env.AWS_REGION || "us-east-1",
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  },
});

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      return Response.json({ error: "未授权" }, { status: 401 });
    }

    const { id: recordingId } = await params;
    const recording = await RecordingService.getRecordingById(recordingId);

    if (!recording) {
      return Response.json({ error: "录音不存在" }, { status: 404 });
    }

    // 检查用户权限
    if (recording.userId !== session.user.id) {
      return Response.json({ error: "无权限访问" }, { status: 403 });
    }

    // 从 S3 URL 提取 bucket 和 key
    const url = new URL(recording.audioUrl);
    const pathParts = url.pathname.split("/");
    const bucket = url.hostname.split(".")[0];
    const key = pathParts.slice(1).join("/");

    try {
      // 检查文件是否存在且可访问
      const command = new HeadObjectCommand({
        Bucket: bucket,
        Key: key,
      });

      await s3.send(command);

      return Response.json({
        accessible: true,
        url: recording.audioUrl,
        size: recording.fileSize,
        mimeType: recording.mimeType,
      });
    } catch (error) {
      console.error("S3 文件访问检查失败:", error);
      return Response.json({
        accessible: false,
        error: "文件无法访问",
        url: recording.audioUrl,
      });
    }
  } catch (error) {
    console.error("检查文件访问失败:", error);
    return Response.json({ error: "检查文件访问失败" }, { status: 500 });
  }
}
