/**
 * API Route for Code Generation
 * Runs httpsnippet on the server to avoid browser compatibility issues
 */

import { NextRequest, NextResponse } from 'next/server'
import { HTTPSnippet } from '@hoppscotch/httpsnippet'

interface CodegenRequest {
  harRequest: {
    method: string
    url: string
    httpVersion: string
    cookies: Array<{ name: string; value: string }>
    headers: Array<{ name: string; value: string }>
    queryString: Array<{ name: string; value: string }>
    postData?: {
      mimeType: string
      text?: string
      params?: Array<{ name: string; value?: string; fileName?: string; contentType?: string }>
    }
    headersSize: number
    bodySize: number
  }
  lang: string
  client: string
}

export async function POST(request: NextRequest) {
  try {
    const body: CodegenRequest = await request.json()
    
    if (!body.harRequest || !body.lang || !body.client) {
      return NextResponse.json(
        { success: false, error: 'Missing required fields: harRequest, lang, client' },
        { status: 400 }
      )
    }

    // Create HTTPSnippet instance
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const snippet = new HTTPSnippet(body.harRequest as any)

    // Generate code
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const code = snippet.convert(body.lang as any, body.client, {
      indent: '  ',
    })

    if (typeof code === 'string') {
      return NextResponse.json({ success: true, code })
    }

    if (Array.isArray(code) && code.length > 0) {
      return NextResponse.json({ success: true, code: code[0] })
    }

    return NextResponse.json(
      { success: false, error: 'Code generation returned unexpected result' },
      { status: 500 }
    )
  } catch (error) {
    console.error('Code generation error:', error)
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : 'Unknown error during code generation' 
      },
      { status: 500 }
    )
  }
}
