import { config } from 'dotenv'
config()

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

async function getPrisma() {
  const { db } = await import('./lib/db')
  return db
}

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 processFolder(prisma: any, roomName: string, folderPath: string, openinaryFolder: string) {
  console.log(`\n--- İşleniyor: ${roomName} ---`)
  const room = await prisma.room.findFirst({
    where: { nameTr: { contains: roomName } }
  })

  if (!room) {
    console.error(`Oda bulunamadı: ${roomName}`)
    return
  }

  console.log(`Oda bulundu: ${room.nameTr} (ID: ${room.id})`)

  const imagesDir = path.join(__dirname, 'public', folderPath)
  if (!fs.existsSync(imagesDir)) {
    console.error(`Klasör bulunamadı: ${imagesDir}`)
    return
  }
  
  const files = fs.readdirSync(imagesDir).filter(f => !f.startsWith('.'))
  const uploadedUrls: string[] = []

  console.log(`${files.length} resim bulundu. Yükleniyor...`)

  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    console.log(`Yükleniyor: ${file} (${i+1}/${files.length})...`)
    try {
      const result = await uploadToOpeninary(path.join(imagesDir, file), openinaryFolder)
      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(`  -> Başarılı: ${finalUrl}`)
    } catch (err) {
      console.error(`  -> Hata:`, err)
    }
  }

  if (uploadedUrls.length > 0) {
    console.log('Veritabanı güncelleniyor...')
    await prisma.room.update({
      where: { id: room.id },
      data: {
        imageUrl: uploadedUrls[0],
        images: uploadedUrls
      }
    })
    console.log(`${roomName} veritabanı güncellendi!`)
  }
}

async function main() {
  const prisma = await getPrisma()
  await processFolder(prisma, 'Süit Daire 1', '1+1', 'starapart/SUITE_1_1')
  await processFolder(prisma, 'Küçük Oda 1 (3 Kişilik)', '1+0', 'starapart/STUDIO_1_0')
  await prisma.$disconnect()
}

main().catch(console.error)
