import { GoogleGenAI } from '@google/genai'
import { NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase'

export async function POST(request: Request) {
  try {
    const { prompt, trainerId, filename } = await request.json()

    const apiKey = process.env.GEMINI_API_KEY
    if (!apiKey) {
      return NextResponse.json(
        { error: 'GEMINI_API_KEY not configured' },
        { status: 500 }
      )
    }

    const ai = new GoogleGenAI({ apiKey })

    const config = {
      imageConfig: {
        aspectRatio: '1:1',
        imageSize: '1K',
      },
      responseModalities: ['IMAGE', 'TEXT'] as string[],
    }

    const response = await ai.models.generateContentStream({
      model: 'gemini-3.1-flash-image-preview',
      config,
      contents: [{ role: 'user', parts: [{ text: prompt }] }],
    })

    const images: { buffer: Buffer; mimeType: string }[] = []

    for await (const chunk of response) {
      const parts = chunk.candidates?.[0]?.content?.parts
      if (!parts) continue

      for (const part of parts) {
        if (part.inlineData) {
          images.push({
            buffer: Buffer.from(part.inlineData.data || '', 'base64'),
            mimeType: part.inlineData.mimeType || 'image/png',
          })
        }
      }
    }

    if (images.length === 0) {
      return NextResponse.json(
        { error: 'No images generated' },
        { status: 500 }
      )
    }

    // Save first image to storage
    const image = images[0]
    const path = `${trainerId}/${filename}`

    const { error } = await supabase.storage
      .from('trainer-avatars')
      .upload(path, image.buffer, {
        contentType: image.mimeType,
        upsert: true,
      })

    if (error) {
      return NextResponse.json(
        { error: `Failed to upload avatar: ${error.message}` },
        { status: 500 }
      )
    }

    const { data: { publicUrl } } = supabase.storage
      .from('trainer-avatars')
      .getPublicUrl(path)

    return NextResponse.json({ url: publicUrl })
  } catch (error) {
    console.error('Avatar generation failed:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Generation failed' },
      { status: 500 }
    )
  }
}
