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

export async function POST(
  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 originalRun = await prisma.simulatorRun.findFirst({
      where: {
        id,
        userId: user.id,
      },
      include: {
        prompt: true,
        promptVersion: true,
        model: true,
      }
    });

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

    // 创建副本名称
    const copyName = `${originalRun.name}${originalRun.name.includes('Copy') || originalRun.name.includes('副本') ? '' : ' Copy'}`;

    // 创建新的运行记录（副本）
    const duplicateRun = await prisma.simulatorRun.create({
      data: {
        userId: user.id,
        name: copyName,
        promptId: originalRun.promptId,
        promptVersionId: originalRun.promptVersionId,
        modelId: originalRun.modelId,
        userInput: originalRun.userInput,
        promptContent: originalRun.promptContent,
        temperature: originalRun.temperature,
        maxTokens: originalRun.maxTokens,
        topP: originalRun.topP,
        frequencyPenalty: originalRun.frequencyPenalty,
        presencePenalty: originalRun.presencePenalty,
        status: "pending", // 副本状态为pending，可以重新运行
        // 不复制输出相关字段：output, error, inputTokens, outputTokens, totalCost, duration, completedAt
      },
      select: {
        id: true,
        name: true,
        status: true,
        userInput: true,
        createdAt: true,
        prompt: {
          select: { id: true, name: true }
        },
        model: {
          select: { id: true, name: true, provider: true }
        }
      }
    });

    return NextResponse.json(duplicateRun, { status: 201 });
  } catch (error) {
    console.error("Error duplicating simulator run:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}