package config

import (
	"context"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"log"
)

// MinioSetup struct
type MinioStorage struct {
	Cfg *Config
}

func NewMinio(cfg *Config) *MinioStorage {
	minioSetup := &MinioStorage{
		Cfg: cfg,
	}

	return minioSetup
}

func (_minio *MinioStorage) ConnectMinio() (*minio.Client, error) {
	ctx := context.Background()
	endpoint := _minio.Cfg.ObjectStorage.MinioStorage.Endpoint
	accessKeyID := _minio.Cfg.ObjectStorage.MinioStorage.AccessKeyID
	secretAccessKey := _minio.Cfg.ObjectStorage.MinioStorage.SecretAccessKey
	useSSL := _minio.Cfg.ObjectStorage.MinioStorage.UseSSL

	bucketName := _minio.Cfg.ObjectStorage.MinioStorage.BucketName
	location := _minio.Cfg.ObjectStorage.MinioStorage.Location

	// Initialize minio client object.
	minioClient, errInit := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: useSSL,
	})
	if errInit != nil {
		log.Fatalln(errInit)
	}

	err := minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: location})
	if err != nil {
		// Check to see if we already own this bucket (which happens if you run this twice)
		exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
		if errBucketExists == nil && exists {
			log.Printf("We already own %s\n", bucketName)
		} else {
			log.Fatalln(err)
		}
	} else {
		log.Printf("Successfully created %s\n", bucketName)
	}
	return minioClient, errInit
}
