package storage

import (
	"context"
	"errors"
	"io"
	"kra/internal/biz/system"
	"sync"

	"kra/internal/config"
)

type Reloadable struct {
	mu      sync.RWMutex
	current system.FileStorage
}

func NewFileStorage(runtime *config.Store) (*Reloadable, error) {
	var config *config.Admin
	if runtime != nil {
		config = runtime.Admin()
	}
	return NewReloadable(config)
}

func NewReloadable(config *config.Admin) (*Reloadable, error) {
	current, err := New(config)
	if err != nil {
		return nil, err
	}
	return &Reloadable{current: current}, nil
}

func (s *Reloadable) Replace(current system.FileStorage) {
	if s == nil {
		return
	}
	s.mu.Lock()
	s.current = current
	s.mu.Unlock()
}

func (s *Reloadable) active() (system.FileStorage, error) {
	if s == nil {
		return nil, errors.New("file storage is unavailable")
	}
	s.mu.RLock()
	current := s.current
	s.mu.RUnlock()
	if current == nil {
		return nil, errors.New("file storage is unavailable")
	}
	return current, nil
}

func (s *Reloadable) Put(ctx context.Context, name string, reader io.Reader) (*system.StoredFile, error) {
	current, err := s.active()
	if err != nil {
		return nil, err
	}
	return current.Put(ctx, name, reader)
}
func (s *Reloadable) Open(ctx context.Context, name string) (io.ReadCloser, error) {
	current, err := s.active()
	if err != nil {
		return nil, err
	}
	return current.Open(ctx, name)
}
func (s *Reloadable) Delete(ctx context.Context, name string) error {
	current, err := s.active()
	if err != nil {
		return err
	}
	return current.Delete(ctx, name)
}
func (s *Reloadable) Compose(ctx context.Context, names []string, destination string) (*system.StoredFile, string, error) {
	current, err := s.active()
	if err != nil {
		return nil, "", err
	}
	return current.Compose(ctx, names, destination)
}
func (s *Reloadable) DeletePrefix(ctx context.Context, prefix string) error {
	current, err := s.active()
	if err != nil {
		return err
	}
	return current.DeletePrefix(ctx, prefix)
}
func (s *Reloadable) List(ctx context.Context, prefix, cursor string, limit int) ([]*system.StoredFile, string, bool, error) {
	current, err := s.active()
	if err != nil {
		return nil, "", false, err
	}
	return current.List(ctx, prefix, cursor, limit)
}
