package system

import (
	"context"
	"encoding/json"
	"errors"
	"testing"

	"kra/internal/config"
)

type initializationRepoStub struct {
	initializeErr error
	reloadErr     error
}

func (*initializationRepoStub) IsInitialized(context.Context) (bool, error) { return false, nil }
func (r *initializationRepoStub) Initialize(context.Context, *DatabaseConfig) error {
	return r.initializeErr
}
func (*initializationRepoStub) PersistConfig(context.Context) error { return nil }
func (*initializationRepoStub) PersistRuntimeConfig(context.Context, *config.Config) error {
	return nil
}
func (r *initializationRepoStub) ReloadConfig(context.Context) error { return r.reloadErr }
func (*initializationRepoStub) ConfigurationJSON() (json.RawMessage, error) {
	return json.RawMessage(`{}`), nil
}
func (*initializationRepoStub) SaveConfigurationJSON(context.Context, json.RawMessage) error {
	return nil
}
func (*initializationRepoStub) DiskMountPoints() []string { return nil }

type taskReloaderStub struct{ err error }

func (r taskReloaderStub) Reload(context.Context) error { return r.err }

func TestInitializeClassifiesPostCommitTaskReloadFailure(t *testing.T) {
	reloadErr := errors.New("scheduler unavailable")
	uc := NewSystemConfigUsecase(&initializationRepoStub{}, taskReloaderStub{err: reloadErr}, nil)
	err := uc.Initialize(context.Background(), &DatabaseConfig{})
	if !errors.Is(err, ErrTaskRuntimeReload) || !errors.Is(err, reloadErr) {
		t.Fatalf("Initialize() error = %v", err)
	}
}

func TestReloadConfigClassifiesMissingTaskRuntime(t *testing.T) {
	uc := NewSystemConfigUsecase(&initializationRepoStub{}, nil, nil)
	err := uc.ReloadConfig(context.Background())
	if !errors.Is(err, ErrTaskRuntimeReload) {
		t.Fatalf("ReloadConfig() error = %v", err)
	}
}

func TestSystemConfigUsecaseRejectsMissingRepository(t *testing.T) {
	uc := NewSystemConfigUsecase(nil, nil, nil)
	if _, err := uc.IsInitialized(context.Background()); err == nil {
		t.Fatal("IsInitialized accepted a missing repository")
	}
	if _, err := uc.ConfigurationJSON(); err == nil {
		t.Fatal("ConfigurationJSON accepted a missing repository")
	}
}
