import { NextRequest, NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"

export async function POST(request: NextRequest, props: { params: Promise<{ trace_id: string }> }) {
  const params = await props.params
  try {
    const { trace_id } = params
    const body = await request.json()
    const { fileKey, modifiedCode, secret } = body

    if (secret !== "codeflash-edit-2025") {
      //console.log("Secret mismatch. Expected: codeflash-edit-2025, Received:", secret)
      return NextResponse.json({ error: "Invalid secret" }, { status: 401 })
    }

    if (!trace_id || !fileKey || !modifiedCode) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 })
    }

    // Get current optimization feature
    const optimizationFeature = await prisma.optimization_features.findUnique({
      where: { trace_id },
      select: {
        metadata: true,
        experiment_metadata: true,
      },
    })

    if (!optimizationFeature) {
      return NextResponse.json({ error: "Trace not found" }, { status: 404 })
    }

    // Get existing metadata and experiment_metadata
    const existingMetadata = (optimizationFeature.metadata as any) || {}
    const experimentMetadata = (optimizationFeature.experiment_metadata as any) || {}

    // Check if diffContents exists and has the fileKey
    if (!experimentMetadata.diffContents || !experimentMetadata.diffContents[fileKey]) {
      return NextResponse.json({ error: "File not found in experiment metadata" }, { status: 404 })
    }

    // Backup original code if not already backed up
    const originalCode = existingMetadata.originalCode || {}
    if (!originalCode[fileKey]) {
      originalCode[fileKey] = experimentMetadata.diffContents[fileKey].newContent
    }

    // Update experiment_metadata with modified code
    const updatedExperimentMetadata = {
      ...experimentMetadata,
      diffContents: {
        ...experimentMetadata.diffContents,
        [fileKey]: {
          ...experimentMetadata.diffContents[fileKey],
          newContent: modifiedCode,
        },
      },
    }

    // Update metadata with backup and tracking info
    const updatedMetadata = {
      ...existingMetadata,
      originalCode,
      lastModified: new Date().toISOString(),
      modifiedBy: "edit-interface",
    }

    // Update the record with both experiment_metadata and metadata
    const result = await prisma.optimization_features.update({
      where: { trace_id },
      data: {
        experiment_metadata: updatedExperimentMetadata,
        metadata: updatedMetadata,
      },
    })

    console.log("Database update successful for trace:", trace_id)

    return NextResponse.json({
      success: true,
      message: "Modified code saved successfully",
    })
  } catch (error) {
    console.error("Error saving modified code:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}
