import { NextRequest, NextResponse } from "next/server";
import { createServerSupabaseClient } from "@/lib/supabase-server";
import { prisma } from "@/lib/prisma";

export async function GET(request: NextRequest) {
  try {
    const supabase = await createServerSupabaseClient();
    const { data: { user }, error: authError } = await supabase.auth.getUser();
    
    if (authError || !user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get("page") || "1");
    const limit = parseInt(searchParams.get("limit") || "20");
    const status = searchParams.get("status");
    
    const skip = (page - 1) * limit;
    
    const where = {
      userId: user.id,
      ...(status && { status }),
    };

    const [runs, total] = await Promise.all([
      prisma.simulatorRun.findMany({
        where,
        select: {
          id: true,
          name: true,
          status: true,
          userInput: true,
          output: true,
          error: true,
          createdAt: true,
          completedAt: true,
          inputTokens: true,
          outputTokens: true,
          totalCost: true,
          duration: true,
          prompt: {
            select: { id: true, name: true }
          },
          model: {
            select: { id: true, name: true, provider: true }
          }
        },
        orderBy: { createdAt: "desc" },
        skip,
        take: limit,
      }),
      prisma.simulatorRun.count({ where }),
    ]);

    return NextResponse.json({
      runs,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error("Error fetching simulator runs:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const supabase = await createServerSupabaseClient();
    const { data: { user }, error: authError } = await supabase.auth.getUser();
    
    if (authError || !user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const {
      name,
      promptId,
      promptVersionId,
      modelId,
      userInput,
      promptContent,
      temperature = 0.7,
      maxTokens,
      topP,
      frequencyPenalty,
      presencePenalty,
      // 用于创建新prompt的字段
      createNewPrompt,
      newPromptName,
      newPromptContent,
    } = body;

    let finalPromptId = promptId;

    // 如果是创建新prompt模式
    if (createNewPrompt && newPromptContent) {
      // 创建新的prompt
      const newPrompt = await prisma.prompt.create({
        data: {
          userId: user.id,
          name: newPromptName || name || "New Prompt",
          content: newPromptContent,
          visibility: "private",
        },
      });
      finalPromptId = newPrompt.id;
    } else if (promptId) {
      // 验证用户是否拥有该prompt
      const prompt = await prisma.prompt.findFirst({
        where: {
          id: promptId,
          userId: user.id,
        },
      });

      if (!prompt) {
        return NextResponse.json({ error: "Prompt not found" }, { status: 404 });
      }
    } else {
      return NextResponse.json({ error: "Either promptId or newPromptContent is required" }, { status: 400 });
    }

    // 验证模型是否可用
    const model = await prisma.model.findUnique({
      where: { id: modelId },
      include: { subscriptionPlan: true }
    });

    if (!model || !model.isActive) {
      return NextResponse.json({ error: "Model not available" }, { status: 400 });
    }

    // 创建运行记录
    const run = await prisma.simulatorRun.create({
      data: {
        userId: user.id,
        name: name || "Simulation Run",
        promptId: finalPromptId,
        promptVersionId,
        modelId,
        userInput,
        promptContent,
        temperature,
        maxTokens,
        topP,
        frequencyPenalty,
        presencePenalty,
        status: "pending",
      },
      include: {
        prompt: {
          select: { id: true, name: true }
        },
        model: {
          select: { id: true, name: true, provider: true, modelId: true }
        }
      }
    });

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