import { config } from 'dotenv'
config()

import fs from 'fs'
import path from 'path'

async function uploadToOpeninary(filePath: string, folder: string) {
  const fileBuffer = fs.readFileSync(filePath)
  const ext = path.extname(filePath).toLowerCase()
  let type = 'image/jpeg'
  if (ext === '.png') type = 'image/png'
  if (ext === '.webp') type = 'image/webp'
  
  const blob = new Blob([fileBuffer], { type })
  const formData = new FormData()
  
  formData.append('files', blob, path.basename(filePath))
  formData.append('folder', folder)

  const res = await fetch(`${process.env.OPENINARY_API_URL}/api/upload`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.OPENINARY_API_KEY}` },
    body: formData,
  })

  if (!res.ok) {
    const errorText = await res.text()
    throw new Error('Upload başarısız: ' + errorText)
  }
  
  const data = await res.json()
  return data.files[0]
}

async function main() {
  const imagesDir = path.join(process.cwd(), 'public/galery')
  if (!fs.existsSync(imagesDir)) {
    console.error('Directory not found:', imagesDir)
    return
  }

  const files = fs.readdirSync(imagesDir)
    .filter(file => /\.(jpg|jpeg|png|webp)$/i.test(file))
    .sort()

  const uploadedUrls: string[] = []
  
  for (const file of files) {
    console.log(`Uploading ${file}...`)
    try {
      const result = await uploadToOpeninary(path.join(imagesDir, file), 'starapart/gallery')
      let finalUrl = result.url
      if (finalUrl && finalUrl.startsWith('/')) {
        finalUrl = `${process.env.NEXT_PUBLIC_OPENINARY_URL || 'https://media.ayris.tech'}${finalUrl}`
      }
      uploadedUrls.push(finalUrl)
      console.log(`Uploaded ${file}: ${finalUrl}`)
    } catch (e) {
      console.error(`Failed to upload ${file}:`, e)
    }
  }

  console.log('All uploaded URLs:', JSON.stringify(uploadedUrls, null, 2))
}

main().catch(console.error)
