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

const STORAGE_ROOT = path.resolve(__dirname, 'storage')

function getApiBase(): string {
  return (process.env.API_URL ?? 'http://localhost:4000').replace(/\/$/, '')
}

export async function uploadImage(
  buffer: Buffer,
  folder: string,
  publicId?: string
): Promise<string> {
  const folderPath = path.join(STORAGE_ROOT, folder)
  fs.mkdirSync(folderPath, { recursive: true })

  const filename = publicId
    ? `${publicId}.jpg`
    : `${crypto.randomBytes(16).toString('hex')}.jpg`

  fs.writeFileSync(path.join(folderPath, filename), buffer)

  return `${getApiBase()}/storage/${folder}/${filename}`
}

export async function deleteImage(imageUrl: string): Promise<void> {
  const marker = '/storage/'
  const idx = imageUrl.indexOf(marker)
  if (idx === -1) return
  const relative = imageUrl.slice(idx + marker.length)
  const filePath = path.join(STORAGE_ROOT, relative)
  if (fs.existsSync(filePath)) fs.unlinkSync(filePath)
}
