import { S3Client, CreateBucketCommand, HeadBucketCommand } from '@aws-sdk/client-s3';

const minioEndpoint = process.env.MINIO_ENDPOINT || 'http://localhost:9000';
const accessKeyId = process.env.MINIO_ACCESS_KEY || 'minio_admin';
const secretAccessKey = process.env.MINIO_SECRET_KEY || 'minio_password_2026';
export const BUCKET_NAME = process.env.MINIO_BUCKET || 'secure-assets';

export const s3Client = new S3Client({
  endpoint: minioEndpoint,
  region: 'us-east-1',
  credentials: {
    accessKeyId,
    secretAccessKey,
  },
  forcePathStyle: true,
});

export async function ensureBucketExists() {
  try {
    await s3Client.send(new HeadBucketCommand({ Bucket: BUCKET_NAME }));
    console.log(`[MinIO] Bucket "${BUCKET_NAME}" already exists.`);
  } catch (err: any) {
    // If the bucket doesn't exist, create it
    if (err.name === 'NotFound' || err.$metadata?.httpStatusCode === 404) {
      console.log(`[MinIO] Bucket "${BUCKET_NAME}" not found. Creating it...`);
      try {
        await s3Client.send(new CreateBucketCommand({ Bucket: BUCKET_NAME }));
        console.log(`[MinIO] Bucket "${BUCKET_NAME}" created successfully.`);
      } catch (createErr) {
        console.error(`[MinIO] Failed to create bucket "${BUCKET_NAME}":`, createErr);
      }
    } else {
      console.error('[MinIO] HeadBucket error:', err);
    }
  }
}
