/*
 * Copyright © 2024 Clyso GmbH
 *
 * 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 storage

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"

	"github.com/clyso/chorus/pkg/dom"
	"github.com/clyso/chorus/pkg/tasks"
)

const (
	lastListedObjTTL = time.Hour * 8
)

var (
	luaDeleteKeysByPrefix = redis.NewScript(`local keys = redis.call('keys', ARGV[1])
if #keys >0 then
	return redis.call('DEL', unpack(keys))
else
	return 0
end`)
)

type Service interface {
	GetLastListedObj(ctx context.Context, task tasks.MigrateBucketListObjectsPayload) (string, error)
	SetLastListedObj(ctx context.Context, task tasks.MigrateBucketListObjectsPayload, val string) error
	DelLastListedObj(ctx context.Context, task tasks.MigrateBucketListObjectsPayload) error
	CleanLastListedObj(ctx context.Context, fromStor, toStor, fromBucket string, toBucket string) error

	StoreUploadID(ctx context.Context, user, bucket, object, uploadID string, ttl time.Duration) error
	DeleteUploadID(ctx context.Context, user, bucket, object, uploadID string) error
	ExistsUploadID(ctx context.Context, user, bucket, object, uploadID string) (bool, error)
	ExistsUploadsForUser(ctx context.Context, user string) (bool, error)
	ExistsUploads(ctx context.Context, user, bucket string) (bool, error)
}

func New(client redis.UniversalClient) Service {
	return &svc{client: client}
}

type svc struct {
	client redis.UniversalClient
}

func (s *svc) CleanLastListedObj(ctx context.Context, fromStor string, toStor string, fromBucket string, toBucket string) error {
	key := fmt.Sprintf("s:%s:%s:%s:%s", fromStor, toStor, fromBucket, toBucket)
	if err := s.client.Del(ctx, key).Err(); err != nil {
		return err
	}
	prefix := key + ":*"
	return luaDeleteKeysByPrefix.Run(ctx, s.client, []string{}, prefix).Err()
}

func (s *svc) DelLastListedObj(ctx context.Context, task tasks.MigrateBucketListObjectsPayload) error {
	fromBucket, toBucket := task.ID.FromToBuckets(task.Bucket)
	key := fmt.Sprintf("s:%s:%s:%s:%s", task.ID.FromStorage(), task.ID.ToStorage(), fromBucket, toBucket)
	if task.Prefix != "" {
		key += ":" + task.Prefix
	}
	return s.client.Del(ctx, key).Err()
}

func (s *svc) GetLastListedObj(ctx context.Context, task tasks.MigrateBucketListObjectsPayload) (string, error) {
	fromBucket, toBucket := task.ID.FromToBuckets(task.Bucket)
	key := fmt.Sprintf("s:%s:%s:%s:%s", task.ID.FromStorage(), task.ID.ToStorage(), fromBucket, toBucket)
	if task.Prefix != "" {
		key += ":" + task.Prefix
	}
	val, err := s.client.Get(ctx, key).Result()
	if errors.Is(err, redis.Nil) {
		return "", nil
	}
	return val, err
}

func (s *svc) SetLastListedObj(ctx context.Context, task tasks.MigrateBucketListObjectsPayload, val string) error {
	fromBucket, toBucket := task.ID.FromToBuckets(task.Bucket)
	key := fmt.Sprintf("s:%s:%s:%s:%s", task.ID.FromStorage(), task.ID.ToStorage(), fromBucket, toBucket)
	if task.Prefix != "" {
		key += ":" + task.Prefix
	}
	return s.client.Set(ctx, key, val, lastListedObjTTL).Err()
}

func (s *svc) StoreUploadID(ctx context.Context, user, bucket, object, uploadID string, ttl time.Duration) error {
	if user == "" {
		return fmt.Errorf("%w: user is required to set uploadID", dom.ErrInvalidArg)
	}
	if bucket == "" {
		return fmt.Errorf("%w: bucket is required to set uploadID", dom.ErrInvalidArg)
	}
	if uploadID == "" {
		return fmt.Errorf("%w: uploadID is required", dom.ErrInvalidArg)
	}
	key := fmt.Sprintf("s:up:%s:%s", user, bucket)
	val := fmt.Sprintf("%s:%s", object, uploadID)
	err := s.client.SAdd(ctx, key, val).Err()
	if err != nil {
		return err
	}
	_ = s.client.Expire(ctx, key, ttl)
	return nil
}

func (s *svc) ExistsUploadID(ctx context.Context, user, bucket, object, uploadID string) (bool, error) {
	if user == "" {
		return false, fmt.Errorf("%w: user is required to set uploadID", dom.ErrInvalidArg)
	}
	if bucket == "" {
		return false, fmt.Errorf("%w: bucket is required to set uploadID", dom.ErrInvalidArg)
	}
	if uploadID == "" {
		return false, fmt.Errorf("%w: uploadID is required", dom.ErrInvalidArg)
	}
	key := fmt.Sprintf("s:up:%s:%s", user, bucket)
	val := fmt.Sprintf("%s:%s", object, uploadID)
	return s.client.SIsMember(ctx, key, val).Result()
}

func (s *svc) ExistsUploadsForUser(ctx context.Context, user string) (bool, error) {
	if user == "" {
		return false, fmt.Errorf("%w: user is required to set uploadID", dom.ErrInvalidArg)
	}
	key := fmt.Sprintf("s:up:%s:*", user)
	res, _, err := s.client.Scan(ctx, 0, key, 1).Result()
	if err != nil {
		return false, err
	}
	return len(res) != 0, nil
}

func (s *svc) ExistsUploads(ctx context.Context, user, bucket string) (bool, error) {
	if user == "" {
		return false, fmt.Errorf("%w: user is required to set uploadID", dom.ErrInvalidArg)
	}
	if bucket == "" {
		return false, fmt.Errorf("%w: bucket is required to set uploadID", dom.ErrInvalidArg)
	}
	key := fmt.Sprintf("s:up:%s:%s", user, bucket)
	num, err := s.client.SCard(ctx, key).Result()
	if err != nil {
		return false, err
	}
	return num > 0, nil
}

func (s *svc) DeleteUploadID(ctx context.Context, user, bucket, object, uploadID string) error {
	if user == "" {
		return fmt.Errorf("%w: user is required to set uploadID", dom.ErrInvalidArg)
	}
	if bucket == "" {
		return fmt.Errorf("%w: bucket is required to set uploadID", dom.ErrInvalidArg)
	}
	if uploadID == "" {
		return fmt.Errorf("%w: uploadID is required", dom.ErrInvalidArg)
	}
	key := fmt.Sprintf("s:up:%s:%s", user, bucket)
	val := fmt.Sprintf("%s:%s", object, uploadID)
	return s.client.SRem(ctx, key, val).Err()
}
