import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { NextRequest } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";

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 POST(req: NextRequest) {
  try {
    // 验证用户身份
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return Response.json({ error: "未授权" }, { status: 401 });
    }

    const { fileName, fileType } = await req.json();

    if (!fileName || !fileType) {
      return Response.json({ error: "缺少必要参数" }, { status: 400 });
    }

    // 生成唯一的文件名，包含用户ID和时间戳
    const userId = session.user.id || session.user.email;
    const timestamp = Date.now();
    const uniqueFileName = `recordings/${userId}/${timestamp}-${fileName}`;

    const command = new PutObjectCommand({
      Bucket: process.env.AWS_S3_BUCKET!,
      Key: uniqueFileName,
      ContentType: fileType,
    });

    const url = await getSignedUrl(s3, command, { expiresIn: 300 }); // 5分钟有效

    return Response.json({
      url,
      fileName: uniqueFileName,
    });
  } catch (error) {
    console.error("生成上传凭证失败:", error);
    return Response.json({ error: "生成上传凭证失败" }, { status: 500 });
  }
}
