package client

import (
	"bytes"
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
)

type FileConfig interface {
	GetAccessKeyID() string
	GetAccessKeySecret() string
	GetEndpoint() string
	GetBucketName() string
	GetHostURL() string
}

const _awsRegion = "us-east-1"
const _s3ACL = "public-read"

type S3FileClientImpl struct {
	s3  *s3.S3
	cfg FileConfig
}

func NewFileClient(fileCfg FileConfig) *S3FileClientImpl {
	sess, err := session.NewSession(&aws.Config{
		S3ForcePathStyle: aws.Bool(true),
		Endpoint:         aws.String(fileCfg.GetEndpoint()),
		Region:           aws.String(_awsRegion),
		Credentials:      credentials.NewStaticCredentials(fileCfg.GetAccessKeyID(), fileCfg.GetAccessKeySecret(), ""),
	})

	if err != nil {
		fmt.Println("Failed to create AWS session:", err)
		return nil
	}

	return &S3FileClientImpl{
		s3:  s3.New(sess),
		cfg: fileCfg,
	}
}

func (r *S3FileClientImpl) UploadFile(ctx context.Context, fileName string, fileContent []byte) (fileUrl string, err error) {
	reader := bytes.NewReader(fileContent)

	_, err = r.s3.PutObject(&s3.PutObjectInput{
		Bucket: aws.String(r.cfg.GetBucketName()),
		Key:    aws.String(fileName),
		Body:   reader,
		ACL:    aws.String(_s3ACL),
	})

	return r.GetPublicURL(fileName), err
}

func (r *S3FileClientImpl) GetPublicURL(fileName string) string {
	if fileName == "" {
		return ""
	}
	return fmt.Sprintf("%s%s%s", r.cfg.GetHostURL(), r.cfg.GetBucketName(), fileName)
}
