package minio

import (
	"context"
	"fmt"
	"io"
	"net/http"

	"gitea.pena/PenaSide/hlog"
	"github.com/minio/minio-go/v7"
)

type Deps struct {
	HLogger hlog.Logger
	Store   *minio.Client
}

type BlobStore struct {
	log   hlog.Logger
	store *minio.Client
}

const (
	bucket = "3c580be9-cf31f296-d055-49cf-b39e-30c7959dc17b"
	folder = "angelsight"
)

func New(ctx context.Context, deps Deps) (*BlobStore, error) {
	bStore := &BlobStore{
		log:   deps.HLogger.Module("minio"),
		store: deps.Store,
	}

	bucketExists, err := bStore.store.BucketExists(ctx, bucket)
	if err != nil {
		return nil, err
	}

	if !bucketExists {
		if err := bStore.store.MakeBucket(ctx, bucket, minio.MakeBucketOptions{}); err != nil {
			return nil, err
		}
	}

	return bStore, nil
}

func (bs *BlobStore) PutFile(
	ctx context.Context,
	filename string,
	reader io.Reader,
	size int64) error {
	info, err := bs.store.PutObject(ctx, bucket, folder+"/"+filename, reader, size, minio.PutObjectOptions{
		//UserMetadata:            nil,
		//UserTags:                nil,
		//Progress:                nil,
		//ContentType:             "",
		//ContentEncoding:         "",
		//ContentDisposition:      "",
		//ContentLanguage:         "",
		//CacheControl:            "",
		//Mode:                    "",
		//RetainUntilDate:         time.Time{},
		//ServerSideEncryption:    nil,
		//NumThreads:              0,
		//StorageClass:            "",
		//WebsiteRedirectLocation: "",
		//PartSize:                0,
		//LegalHold:               "",
		//SendContentMd5:          false,
		//DisableMultipart:        false,
		//Internal:                minio.AdvancedPutOptions{},
	})
	if err != nil {
		fmt.Println(err)
		return err
	}
	fmt.Println("info", info)

	return nil
}

func (bs *BlobStore) DeleteFile(ctx context.Context, id string) error {
	if err := bs.store.RemoveObject(ctx, bucket, folder+"/"+id, minio.RemoveObjectOptions{
		//GovernanceBypass: false,
		//VersionID:        "",
		//Internal:         AdvancedRemoveOptions
	}); err != nil {
		return err
	}

	return nil
}

func (bs *BlobStore) FileExists(ctx context.Context, filename string) (bool, error) {
	_, err := bs.store.StatObject(ctx, bucket, folder+"/"+filename, minio.StatObjectOptions{})
	if err != nil {
		if minio.ToErrorResponse(err).StatusCode == http.StatusNotFound {
			return false, nil
		}
		return false, err
	}
	return true, nil
}
