import fs from 'fs';
import path from 'path';
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { s3Client, BUCKET_NAME, ensureBucketExists } from './utils/s3';

async function migrateLocalUploads() {
  console.log('[Migration] Starting local uploads migration to MinIO...');
  await ensureBucketExists();

  const localUploadsDir = path.join(__dirname, '../../minio-seed');
  if (!fs.existsSync(localUploadsDir)) {
    console.log('[Migration] No local uploads directory found.');
    return;
  }

  const files = fs.readdirSync(localUploadsDir);
  console.log(`[Migration] Found ${files.length} local files.`);

  for (const file of files) {
    const filePath = path.join(localUploadsDir, file);
    const stat = fs.statSync(filePath);
    
    if (stat.isFile()) {
      console.log(`[Migration] Uploading "${file}" to MinIO bucket "${BUCKET_NAME}"...`);
      const fileBuffer = fs.readFileSync(filePath);
      
      let contentType = 'application/octet-stream';
      if (file.endsWith('.pdf')) {
        contentType = 'application/pdf';
      } else if (file.endsWith('.png')) {
        contentType = 'image/png';
      } else if (file.endsWith('.jpg') || file.endsWith('.jpeg')) {
        contentType = 'image/jpeg';
      } else if (file.endsWith('.md')) {
        contentType = 'text/markdown';
      } else if (file.endsWith('.docx')) {
        contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      }

      try {
        await s3Client.send(new PutObjectCommand({
          Bucket: BUCKET_NAME,
          Key: file,
          Body: fileBuffer,
          ContentType: contentType,
        }));
        console.log(`[Migration] Successfully uploaded "${file}".`);
      } catch (err) {
        console.error(`[Migration] Failed to upload "${file}":`, err);
      }
    }
  }

  console.log('[Migration] Migration complete.');
}

migrateLocalUploads().catch(console.error);
