package file_storage

import (
	"context"
	"mime"
	"path/filepath"
	"time"

	"github.com/kzzan/s3kit"
)

type storage struct {
	client *s3kit.Client
	bucket string
}

func NewRustFSStorage(
	endpoint string,
	accessKeyID string,
	secretAccessKey string,
	bucket string,
) (IFileStorage, error) {
	client, err := s3kit.New(s3kit.Config{
		Endpoint:        endpoint,
		AccessKeyID:     accessKeyID,
		SecretAccessKey: secretAccessKey,
		Region:          "ru-1",
	})
	if err != nil {
		return nil, err
	}

	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	err = client.CreateBucket(
		ctx,
		bucket,
	)
	if err != nil {
		return nil, err
	}

	return &storage{
		client: client,
		bucket: bucket,
	}, nil
}

func (s *storage) Put(ctx context.Context, file *File) error {
	mime := s.getMimeType(file.Name)
	return s.client.PutObjectBytes(ctx, s.bucket, file.Name, file.Data, mime)
}

func (s *storage) Get(ctx context.Context, filename string) (*File, error) {
	data, err := s.client.GetObjectBytes(ctx, s.bucket, filename)
	if err != nil {
		return nil, err
	}
	return &File{
		Name: filename,
		Data: data,
		Mime: s.getMimeType(filename),
	}, nil
}

func (s *storage) getMimeType(filename string) string {
	if mimeType := mime.TypeByExtension(filepath.Ext(filename)); mimeType != "" {
		return mimeType
	}
	return "application/octet-stream"
}
