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

export async function POST(request: NextRequest, props: { params: Promise<{ trace_id: string }> }) {
  const params = await props.params
  try {
    const session = await auth0.getSession()
    if (!session?.user?.sub) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    const { trace_id } = params
    const body = await request.json()
    const { fileKey, modifiedCode } = body

    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 Prisma.JsonObject | null) ?? {}
    const experimentMetadata =
      (optimizationFeature.experiment_metadata as Prisma.JsonObject | null) ?? {}

    // Check if diffContents exists and has the fileKey
    const diffContents = experimentMetadata.diffContents as
      | Record<string, Prisma.JsonObject>
      | undefined
    if (!diffContents || !diffContents[fileKey]) {
      return NextResponse.json({ error: "File not found in experiment metadata" }, { status: 404 })
    }

    // Backup original code if not already backed up
    const originalCode: Prisma.JsonObject =
      (existingMetadata.originalCode as Prisma.JsonObject | undefined) ?? {}
    if (!originalCode[fileKey]) {
      originalCode[fileKey] = diffContents[fileKey].newContent
    }

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

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

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

    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 })
  }
}
