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 CLOUDINARY_ROOT = 'salhotel';

async function uploadFile(filePath, cloudinaryFolder) {
  console.log(`Uploading ${filePath} to ${cloudinaryFolder}...`);
  try {
    const result = await cloudinary.uploader.upload(filePath, {
      folder: `${CLOUDINARY_ROOT}/${cloudinaryFolder}`,
      use_filename: true,
      unique_filename: false,
      overwrite: true
    });
    console.log(`Successfully uploaded: ${result.public_id}`);
    return {
      localPath: filePath,
      url: result.secure_url,
      publicId: result.public_id
    };
  } catch (e) {
    console.error(`Failed to upload ${filePath}:`, e.message);
    return null;
  }
}

async function scanAndUpload(dir, currentCloudinaryPath = '') {
  const entries = fs.readdirSync(dir, { withFileTypes: true });
  let results = [];

  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);

    if (entry.isDirectory()) {
      // Normalize folder names for Cloudinary (e.g., konaklama -> rooms)
      let nextCloudinaryPath = currentCloudinaryPath;
      const folderName = entry.name.toLowerCase();

      if (folderName === 'konaklama') nextCloudinaryPath = ''; // Root konaklama
      else if (folderName === 'odalar') nextCloudinaryPath = 'rooms';
      else if (folderName === 'rezidans') nextCloudinaryPath = 'residence';
      else if (folderName === 'restaurant') nextCloudinaryPath = 'dining';
      else {
        nextCloudinaryPath = currentCloudinaryPath ? `${currentCloudinaryPath}/${folderName}` : folderName;
      }

      const recursiveResults = await scanAndUpload(fullPath, nextCloudinaryPath);
      results = results.concat(recursiveResults);
    } else {
      const ext = path.extname(entry.name).toLowerCase();
      if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {
        const uploadResult = await uploadFile(fullPath, currentCloudinaryPath);
        if (uploadResult) {
          results.push(uploadResult);
        }
      }
    }
  }
  return results;
}

async function main() {
  const docsDir = path.join(process.cwd(), 'docs');
  if (!fs.existsSync(docsDir)) {
    console.error('Docs directory not found!');
    return;
  }

  console.log('--- Starting Resort Photos Upload ---');
  const allUploads = await scanAndUpload(docsDir);

  fs.writeFileSync('scratch/resort_upload_report.json', JSON.stringify(allUploads, null, 2));
  console.log(`\nUpload completed! ${allUploads.length} images processed.`);
  console.log('Report saved to scratch/resort_upload_report.json');
}

main();
