#!/usr/bin/env node
/**
 * Setup MinIO Bucket
 *
 * Creates the required bucket for document storage if it doesn't exist
 */

const { S3Client, CreateBucketCommand, HeadBucketCommand } = require('@aws-sdk/client-s3');
require('dotenv').config();

const BUCKET_NAME = 'xpeditis-documents';

// Configure S3 client for MinIO
const s3Client = new S3Client({
  region: process.env.AWS_REGION || 'us-east-1',
  endpoint: process.env.AWS_S3_ENDPOINT || 'http://localhost:9000',
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID || 'minioadmin',
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || 'minioadmin',
  },
  forcePathStyle: true, // Required for MinIO
});

async function setupBucket() {
  console.log('\n🪣 MinIO Bucket Setup');
  console.log('==========================================');
  console.log(`Bucket name: ${BUCKET_NAME}`);
  console.log(`Endpoint: ${process.env.AWS_S3_ENDPOINT || 'http://localhost:9000'}`);
  console.log('');

  try {
    // Check if bucket exists
    console.log('📋 Step 1: Checking if bucket exists...');
    try {
      await s3Client.send(new HeadBucketCommand({ Bucket: BUCKET_NAME }));
      console.log(`✅ Bucket '${BUCKET_NAME}' already exists`);
      console.log('');
      console.log('✅ Setup complete! The bucket is ready to use.');
      process.exit(0);
    } catch (error) {
      if (error.name === 'NotFound' || error.$metadata?.httpStatusCode === 404) {
        console.log(`ℹ️  Bucket '${BUCKET_NAME}' does not exist`);
      } else {
        throw error;
      }
    }

    // Create bucket
    console.log('');
    console.log('📋 Step 2: Creating bucket...');
    await s3Client.send(new CreateBucketCommand({ Bucket: BUCKET_NAME }));
    console.log(`✅ Bucket '${BUCKET_NAME}' created successfully!`);

    // Verify creation
    console.log('');
    console.log('📋 Step 3: Verifying bucket...');
    await s3Client.send(new HeadBucketCommand({ Bucket: BUCKET_NAME }));
    console.log(`✅ Bucket '${BUCKET_NAME}' verified!`);

    console.log('');
    console.log('==========================================');
    console.log('✅ Setup complete! The bucket is ready to use.');
    console.log('');
    console.log('You can now:');
    console.log('  1. Create CSV bookings via the frontend');
    console.log('  2. Upload documents to this bucket');
    console.log('  3. View files at: http://localhost:9001 (MinIO Console)');
    console.log('');

    process.exit(0);
  } catch (error) {
    console.error('');
    console.error('❌ ERROR: Failed to setup bucket');
    console.error('');
    console.error('Error details:');
    console.error(`  Name: ${error.name}`);
    console.error(`  Message: ${error.message}`);
    if (error.$metadata) {
      console.error(`  HTTP Status: ${error.$metadata.httpStatusCode}`);
    }
    console.error('');
    console.error('Common solutions:');
    console.error('  1. Check if MinIO is running: docker ps | grep minio');
    console.error('  2. Verify credentials in .env file');
    console.error('  3. Ensure AWS_S3_ENDPOINT is set correctly');
    console.error('');
    process.exit(1);
  }
}

setupBucket();
