import fs from 'fs';
import path from 'path';
import 'dotenv/config';

async function uploadFile(filePath, folder) {
  const fileName = path.basename(filePath);
  const fileBuffer = fs.readFileSync(filePath);
  
  const blob = new Blob([fileBuffer], { type: 'image/png' });
  
  const formData = new FormData();
  formData.append('files', blob, fileName);
  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 text = await res.text();
    throw new Error(`Upload failed for ${fileName}: ${text}`);
  }

  const data = await res.json();
  return data.files[0].url;
}

async function main() {
  const filePath = './public/kitesurf.png';
  console.log(`Uploading ${filePath}...`);
  try {
    const url = await uploadFile(filePath, 'kitebeachakyaka');
    console.log(`Uploaded! URL: ${url}`);
  } catch (e) {
    console.error(e);
  }
}

main().catch(console.error);
