'use server'

import { uploadToOpeninary } from '@/lib/openinary'

export async function uploadImageAction(formData: FormData) {
  try {
    const file = formData.get('file') as File
    if (!file) throw new Error('No file provided')
    
    const folder = (formData.get('folder') as string) || 'starapart'
    
    const result = await uploadToOpeninary(file, folder)
    let finalUrl = result.url
    if (finalUrl && finalUrl.startsWith('/')) {
      finalUrl = `${process.env.NEXT_PUBLIC_OPENINARY_URL || 'https://media.ayris.tech'}${finalUrl}`
    }
    
    return { success: true, url: finalUrl }
  } catch (error: any) {
    console.error('Upload error:', error)
    return { success: false, error: error.message }
  }
}
