import { NextRequest, NextResponse } from 'next/server'
import { uploadToOpeninary } from '@/lib/openinary'
import { optimizedImage } from '@/lib/openinary-url'

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData()
    const file = formData.get('file') as File

    if (!file) {
      return NextResponse.json({ error: 'Dosya bulunamadı.' }, { status: 400 })
    }

    // Upload to Openinary
    const result = await uploadToOpeninary(file, 'moyqr');

    // Generate optimized URL
    // e.g. "w_800,h_800,c_limit,q_auto,f_auto" parameters format for Openinary
    const optimizedUrl = optimizedImage(result.path, 'w_800,h_800,c_limit,q_auto,f_auto');

    return NextResponse.json({ url: optimizedUrl })
  } catch (error) {
    console.error('Upload error:', error)
    return NextResponse.json({ error: 'Yükleme başarısız oldu.' }, { status: 500 })
  }
}
