const cloudinary = require('cloudinary').v2;
require('dotenv').config({ path: '.env.local' });
const fs = require('fs');
const path = require('path');

cloudinary.config({
  cloud_name: process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET
});

const BASE_DIR = path.join('public', 'images');
const CLOUDINARY_ROOT = 'salmakisyat';

async function uploadFolder(folderName) {
  const folderPath = path.join(BASE_DIR, folderName);
  if (!fs.existsSync(folderPath)) return [];

  const files = fs.readdirSync(folderPath);
  const results = [];

  for (const file of files) {
    const filePath = path.join(folderPath, file);
    if (!fs.lstatSync(filePath).isFile()) continue;

    console.log(`Uploading ${folderName}/${file}...`);
    try {
      const result = await cloudinary.uploader.upload(filePath, {
        folder: `${CLOUDINARY_ROOT}/${folderName}`,
        use_filename: true,
        unique_filename: false,
        overwrite: true
      });
      results.push({
        localFile: file,
        public_id: result.public_id
      });
      console.log(`Done: ${result.public_id}`);
    } catch (e) {
      console.error(`Failed to upload ${file}:`, e.message);
    }
  }
  return results;
}

async function main() {
  const folders = ['meira', 'melda', 'queenofsalmakis', 'dolcemare', 'sunworld'];
  const allResults = {};

  for (const folder of folders) {
    console.log(`\n--- Processing folder: ${folder} ---`);
    allResults[folder] = await uploadFolder(folder);
  }

  fs.writeFileSync('scratch/upload_report.json', JSON.stringify(allResults, null, 2));
  console.log('\nAll uploads completed! Report saved to scratch/upload_report.json');
}

main();
