package storage

import (
	"context"
	"errors"
	"io"
	"testing"
	"time"

	"kra/internal/biz/system"
)

type blockingStorage struct {
	started chan struct{}
	release chan struct{}
}

func (s *blockingStorage) Put(context.Context, string, io.Reader) (*system.StoredFile, error) {
	close(s.started)
	<-s.release
	return &system.StoredFile{Name: "uploaded"}, nil
}
func (*blockingStorage) Open(context.Context, string) (io.ReadCloser, error) {
	return nil, errors.New("not implemented")
}
func (*blockingStorage) Delete(context.Context, string) error { return nil }
func (*blockingStorage) Compose(context.Context, []string, string) (*system.StoredFile, string, error) {
	return nil, "", errors.New("not implemented")
}
func (*blockingStorage) DeletePrefix(context.Context, string) error { return nil }
func (*blockingStorage) List(context.Context, string, string, int) ([]*system.StoredFile, string, bool, error) {
	return nil, "", false, errors.New("not implemented")
}

type emptyStorage struct{}

func (*emptyStorage) Put(context.Context, string, io.Reader) (*system.StoredFile, error) {
	return &system.StoredFile{Name: "replacement"}, nil
}
func (*emptyStorage) Open(context.Context, string) (io.ReadCloser, error) {
	return nil, errors.New("not implemented")
}
func (*emptyStorage) Delete(context.Context, string) error { return nil }
func (*emptyStorage) Compose(context.Context, []string, string) (*system.StoredFile, string, error) {
	return nil, "", errors.New("not implemented")
}
func (*emptyStorage) DeletePrefix(context.Context, string) error { return nil }
func (*emptyStorage) List(context.Context, string, string, int) ([]*system.StoredFile, string, bool, error) {
	return nil, "", false, errors.New("not implemented")
}

func TestReloadableReplaceDoesNotWaitForInFlightOperation(t *testing.T) {
	old := &blockingStorage{started: make(chan struct{}), release: make(chan struct{})}
	reloadable := &Reloadable{current: old}
	putDone := make(chan error, 1)
	go func() {
		_, err := reloadable.Put(context.Background(), "file", nil)
		putDone <- err
	}()
	select {
	case <-old.started:
	case <-time.After(time.Second):
		t.Fatal("storage operation did not start")
	}

	replaced := make(chan struct{})
	go func() {
		reloadable.Replace(&emptyStorage{})
		close(replaced)
	}()
	select {
	case <-replaced:
	case <-time.After(200 * time.Millisecond):
		t.Fatal("Replace waited for an in-flight storage operation")
	}

	close(old.release)
	select {
	case err := <-putDone:
		if err != nil {
			t.Fatalf("Put() error = %v", err)
		}
	case <-time.After(time.Second):
		t.Fatal("storage operation did not finish")
	}
}

func TestReloadableNilStorageReturnsError(t *testing.T) {
	var reloadable *Reloadable
	if _, err := reloadable.Put(context.Background(), "file", nil); err == nil {
		t.Fatal("nil Reloadable.Put() succeeded")
	}
	if _, err := (&Reloadable{}).Open(context.Background(), "file"); err == nil {
		t.Fatal("empty Reloadable.Open() succeeded")
	}
}
