package minio

import (
	"errors"

	a "github.com/karincake/apem"
	lo "github.com/karincake/apem/loggero"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
)

var O MinioCfg = MinioCfg{}
var I *minio.Client

type MinioCfg struct {
	Endpoint   string
	Region     string
	AccessKey  string   `yaml:"accessKey"`
	SecretKey  string   `yaml:"secretKey"`
	UseSsl     bool     `yaml:"useSsl"`
	BucketName []string `yaml:"bucketName"`
}

type ResponsePostPolicy struct {
	Url      string            `json:"url"`
	FormData map[string]string `json:"form-data"`
}

func (c MinioCfg) GetRegion() string {
	return c.Region
}

func (c MinioCfg) GetEndpoint() string {
	return c.Endpoint
}

func (c MinioCfg) GetUseSsl() bool {
	return c.UseSsl
}

func (c MinioCfg) GetBucketName() []string {
	return c.BucketName
}

// connect db
func Connect() {
	a.ParseSingleCfg(&O)
	NewClient(&O)
	if I == nil {
		panic("minio client is nil")
	}
	lo.I.Println("Instantiation for object storage service using Minio, status: DONE!!")
}

func NewClient(cfg *MinioCfg) error {
	// Initialize minio client object.
	endpoint := cfg.Endpoint
	if endpoint == "" {
		return errors.New("config minio endpoint empty")
	}
	accessKey := cfg.AccessKey
	if accessKey == "" {
		return errors.New("config minio access key empty")
	}
	secretKey := cfg.SecretKey
	if secretKey == "" {
		return errors.New("config minio secret key empty")
	}
	useSSL := cfg.UseSsl
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKey, secretKey, ""),
		Secure: useSSL,
	})
	if err != nil {
		return err
	}
	I = minioClient
	return nil
}
