// classes.smartbucket.ts

import * as plugins from './plugins.js';
import { Bucket } from './classes.bucket.js';
import { normalizeStorageDescriptor } from './helpers.js';

export class SmartBucket {
  public config: plugins.tsclass.storage.IStorageDescriptor;

  public storageClient: plugins.s3.S3Client;

  /** @deprecated Use storageClient instead */
  public get s3Client(): plugins.s3.S3Client {
    return this.storageClient;
  }

  /**
   * the constructor of SmartBucket
   */
  constructor(configArg: plugins.tsclass.storage.IStorageDescriptor) {
    this.config = configArg;

    // Use the normalizer to handle various endpoint formats
    const { normalized } = normalizeStorageDescriptor(configArg);

    this.storageClient = new plugins.s3.S3Client({
      endpoint: normalized.endpointUrl,
      region: normalized.region,
      credentials: normalized.credentials,
      forcePathStyle: normalized.forcePathStyle, // Necessary for S3-compatible storage like MinIO or Wasabi
    });
  }

  public async createBucket(bucketNameArg: string) {
    const bucket = await Bucket.createBucketByName(this, bucketNameArg);
    return bucket;
  }

  public async removeBucket(bucketName: string) {
    await Bucket.removeBucketByName(this, bucketName);
  }

  public async getBucketByName(bucketNameArg: string) {
    return Bucket.getBucketByName(this, bucketNameArg);
  }

  /**
   * Check if a bucket exists
   */
  public async bucketExists(bucketNameArg: string): Promise<boolean> {
    const command = new plugins.s3.ListBucketsCommand({});
    const buckets = await this.storageClient.send(command);
    return buckets.Buckets?.some(bucket => bucket.Name === bucketNameArg) ?? false;
  }
}
