import { NextRequest, NextResponse } from "next/server";
import { auth } from '@/lib/auth';
import { headers } from 'next/headers';
import { prisma } from "@/lib/prisma";
import { getSignedImageUrl } from "@/lib/storage";

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const session = await auth.api.getSession({
      headers: await headers()
    });
    
    if (!session?.user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    
    const user = session.user;

    const run = await prisma.simulatorRun.findFirst({
      where: {
        id,
        userId: user.id,
      },
      select: {
        id: true,
        generatedFilePath: true,
        status: true
      }
    });

    if (!run) {
      return NextResponse.json({ error: "Run not found" }, { status: 404 });
    }

    if (!run.generatedFilePath) {
      return NextResponse.json({ error: "No image file found" }, { status: 404 });
    }

    // 生成临时URL，有效期1小时
    try {
      const signedUrl = await getSignedImageUrl(run.generatedFilePath, 3600);
      return NextResponse.json({ fileUrl: signedUrl });
    } catch (error) {
      console.error("Error generating signed URL:", error);
      return NextResponse.json({ error: "Failed to generate image URL" }, { status: 500 });
    }
  } catch (error) {
    console.error("Error fetching image URL:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}