package storage

import (
	"context"
	"io"
	"log"
	"net/url"
	"os"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
)

type FileStorage struct {
	client *minio.Client
}

func New() *FileStorage {
	endpoint := os.Getenv("MINIO_ENDPOINT")
	if endpoint == "" {
		log.Fatalln("MINIO_ENDPOINT env var is required")
		return nil
	}

	accessKey := os.Getenv("MINIO_ACCESS_KEY")
	if accessKey == "" {
		log.Fatalln("MINIO_ACCESS_KEY env var is required")
		return nil
	}

	secretKey := os.Getenv("MINIO_SECRET_KEY")
	if secretKey == "" {
		log.Fatalln("MINIO_SECRET_KEY env var is required")
		return nil
	}

	client, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKey, secretKey, ""),
		Secure: false,
	})
	if err != nil {
		log.Fatalln("Failed to create minio client:", err)
		return nil
	}

	return &FileStorage{
		client,
	}
}

func (fs *FileStorage) PutObject(ctx context.Context, bucketName string, objectName string, reader io.Reader, size int64, opts minio.PutObjectOptions) (minio.UploadInfo, error) {
	return fs.client.PutObject(ctx, bucketName, objectName, reader, size, opts)
}

func (fs *FileStorage) EndpointURL() *url.URL {
	return fs.client.EndpointURL()
}
