/**
 * Script to set MinIO bucket policy for public read access
 *
 * This allows documents to be downloaded directly via URL without authentication
 */

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

const MINIO_ENDPOINT = process.env.AWS_S3_ENDPOINT || 'http://localhost:9000';
const BUCKET_NAME = 'xpeditis-documents';

// Initialize MinIO client
const s3Client = new S3Client({
  region: 'us-east-1',
  endpoint: MINIO_ENDPOINT,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID || 'minioadmin',
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || 'minioadmin',
  },
  forcePathStyle: true,
});

async function setBucketPolicy() {
  try {
    // Policy to allow public read access to all objects in the bucket
    const policy = {
      Version: '2012-10-17',
      Statement: [
        {
          Effect: 'Allow',
          Principal: '*',
          Action: ['s3:GetObject'],
          Resource: [`arn:aws:s3:::${BUCKET_NAME}/*`],
        },
      ],
    };

    console.log('📋 Setting bucket policy for:', BUCKET_NAME);
    console.log('Policy:', JSON.stringify(policy, null, 2));

    // Set the bucket policy
    await s3Client.send(
      new PutBucketPolicyCommand({
        Bucket: BUCKET_NAME,
        Policy: JSON.stringify(policy),
      })
    );

    console.log('\n✅ Bucket policy set successfully!');
    console.log(`   All objects in ${BUCKET_NAME} are now publicly readable`);

    // Verify the policy was set
    console.log('\n🔍 Verifying bucket policy...');
    const getPolicy = await s3Client.send(
      new GetBucketPolicyCommand({
        Bucket: BUCKET_NAME,
      })
    );

    console.log('✅ Current policy:', getPolicy.Policy);

    console.log('\n📝 Note: This allows public read access to all documents.');
    console.log('   For production, consider using signed URLs instead.');
  } catch (error) {
    console.error('❌ Error:', error);
    throw error;
  }
}

setBucketPolicy()
  .then(() => {
    console.log('\n✅ Script completed successfully');
    process.exit(0);
  })
  .catch(error => {
    console.error('\n❌ Script failed:', error);
    process.exit(1);
  });
