import { prisma } from "@codeflash-ai/common"
import { Request, Response } from "express"
import { logger } from "../utils/logger.js"
import {
  validationFailure,
  optimizationNotFound,
  internalServerError,
} from "../exceptions/index.js"

// Dependencies interface for easier testing
export interface OptimizationSuccessDependencies {
  prisma: {
    optimization_events: {
      updateMany: (params: any) => Promise<{ count: number }>
    }
  }
}

// Default dependencies
let dependencies: OptimizationSuccessDependencies = {
  prisma,
}

// For testing - allow dependency injection
export function setOptimizationSuccessDependencies(deps: Partial<OptimizationSuccessDependencies>) {
  dependencies = { ...dependencies, ...deps }
}

export function resetOptimizationSuccessDependencies() {
  dependencies = {
    prisma,
  }
}

export async function optimizationSuccess(req: Request, res: Response): Promise<void> {
  const { trace_id, is_optimization_found } = req.body

  // Fix validation to handle null values properly
  if (trace_id == null || typeof is_optimization_found !== "boolean") {
    throw validationFailure("trace_id and is_optimization_found(boolean) are required")
  }

  try {
    const result = await dependencies.prisma.optimization_events.updateMany({
      where: { trace_id },
      data: { is_optimization_found },
    })

    if (result.count === 0) {
      throw optimizationNotFound(trace_id)
    }

    res.status(200).json({ message: "Optimization status updated." })
  } catch (error) {
    if (error && typeof error === "object" && "getHttpStatus" in error) {
      throw error
    }
    logger.errorWithSentry("Error in markOptimizationSuccess:", req, {}, error as Error)
    throw internalServerError("Error updating optimization status")
  }
}
