// Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package logs

import (
	"context"
	"fmt"
	"io"
	"path"
	"strings"

	"github.com/harness/gitness/app/store"

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

// NewS3Env returns a new S3 log store.
func NewS3LogStore(bucket, prefix, endpoint string, pathStyle bool) store.LogStore {
	disableSSL := false

	if endpoint != "" {
		disableSSL = !strings.HasPrefix(endpoint, "https://")
	}

	return &s3store{
		bucket: bucket,
		prefix: prefix,
		session: session.Must(
			session.NewSession(&aws.Config{
				Endpoint:         aws.String(endpoint),
				DisableSSL:       aws.Bool(disableSSL),
				S3ForcePathStyle: aws.Bool(pathStyle),
			}),
		),
	}
}

type s3store struct {
	bucket  string
	prefix  string
	session *session.Session
}

func (s *s3store) Find(_ context.Context, step int64) (io.ReadCloser, error) {
	svc := s3.New(s.session)
	out, err := svc.GetObject(&s3.GetObjectInput{
		Bucket: aws.String(s.bucket),
		Key:    aws.String(s.key(step)),
	})
	if err != nil {
		return nil, err
	}
	return out.Body, nil
}

func (s *s3store) Create(_ context.Context, step int64, r io.Reader) error {
	uploader := s3manager.NewUploader(s.session)
	input := &s3manager.UploadInput{
		ACL:    aws.String("private"),
		Bucket: aws.String(s.bucket),
		Key:    aws.String(s.key(step)),
		Body:   r,
	}
	_, err := uploader.Upload(input)
	return err
}

func (s *s3store) Update(ctx context.Context, step int64, r io.Reader) error {
	return s.Create(ctx, step, r)
}

func (s *s3store) Delete(_ context.Context, step int64) error {
	svc := s3.New(s.session)
	_, err := svc.DeleteObject(&s3.DeleteObjectInput{
		Bucket: aws.String(s.bucket),
		Key:    aws.String(s.key(step)),
	})
	return err
}

func (s *s3store) key(step int64) string {
	return path.Join("/", s.prefix, fmt.Sprint(step))
}
