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/jpeg' });
  
  const formData = new FormData();
  // We can pass a file name to the formData in Node by passing an object with name or using File (if available)
  // But FormData append takes (name, value, filename)
  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 dirPath = './public/rooms';
  const files = fs.readdirSync(dirPath).filter(f => f.endsWith('.jpeg') || f.endsWith('.jpg'));
  
  const uploadedUrls = [];

  for (const file of files) {
    console.log(`Uploading ${file}...`);
    try {
      const url = await uploadFile(path.join(dirPath, file), 'kitebeachakyaka/rooms');
      console.log(`Uploaded! URL: ${url}`);
      uploadedUrls.push(url);
    } catch (e) {
      console.error(e);
    }
  }

  console.log('\n--- UPLOADED URLS ---');
  console.log(JSON.stringify(uploadedUrls, null, 2));
}

main().catch(console.error);
