package system

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

var ErrTaskRuntimeReload = errors.New("task runtime reload failed")

type TaskRuntimeReloadError struct{ Err error }

func (e *TaskRuntimeReloadError) Error() string        { return e.Err.Error() }
func (e *TaskRuntimeReloadError) Is(target error) bool { return target == ErrTaskRuntimeReload }

type DatabaseConfig struct {
	Driver, Host, Port, User, Password, Name, Path, Config, Template, AdminPassword string
	APIs                                                                            []*API
}

type InitializationRepo interface {
	IsInitialized(context.Context) (bool, error)
	Initialize(context.Context, *DatabaseConfig) error
	PersistConfig(context.Context) error
	PersistAdminConfig(context.Context, []byte) error
	PersistRuntimeConfig(context.Context, []byte, []byte) error
	ReloadConfig(context.Context) error
	ConfigurationJSON() (json.RawMessage, error)
	SaveConfigurationJSON(context.Context, json.RawMessage) error
	DiskMountPoints() []string
}

// TaskReloader is the narrow scheduler boundary needed after configuration
// changes. The consumer owns this interface; worker supplies the implementation.
type TaskReloader interface {
	Reload(context.Context) error
}

type SystemConfigUsecase struct {
	repo  InitializationRepo
	tasks TaskReloader
}

func NewSystemConfigUsecase(repo InitializationRepo, tasks TaskReloader) *SystemConfigUsecase {
	return &SystemConfigUsecase{repo: repo, tasks: tasks}
}

func (uc *SystemConfigUsecase) IsInitialized(ctx context.Context) (bool, error) {
	return uc.repo.IsInitialized(ctx)
}
func (uc *SystemConfigUsecase) Initialize(ctx context.Context, config *DatabaseConfig) error {
	if config == nil {
		return errors.New("数据库初始化参数无效")
	}
	if err := uc.repo.Initialize(ctx, config); err != nil {
		return err
	}
	if err := uc.tasks.Reload(ctx); err != nil {
		return &TaskRuntimeReloadError{Err: err}
	}
	return nil
}
func (uc *SystemConfigUsecase) PersistConfig(ctx context.Context) error {
	return uc.repo.PersistConfig(ctx)
}
func (uc *SystemConfigUsecase) PersistAdminConfig(ctx context.Context, value []byte) error {
	return uc.repo.PersistAdminConfig(ctx, value)
}
func (uc *SystemConfigUsecase) PersistRuntimeConfig(ctx context.Context, data, admin []byte) error {
	return uc.repo.PersistRuntimeConfig(ctx, data, admin)
}
func (uc *SystemConfigUsecase) ReloadConfig(ctx context.Context) error {
	if err := uc.repo.ReloadConfig(ctx); err != nil {
		return err
	}
	if err := uc.tasks.Reload(ctx); err != nil {
		return &TaskRuntimeReloadError{Err: err}
	}
	return nil
}

func (uc *SystemConfigUsecase) ConfigurationJSON() (json.RawMessage, error) {
	return uc.repo.ConfigurationJSON()
}

func (uc *SystemConfigUsecase) SaveConfigurationJSON(ctx context.Context, value json.RawMessage) error {
	return uc.repo.SaveConfigurationJSON(ctx, value)
}

func (uc *SystemConfigUsecase) DiskMountPoints() []string { return uc.repo.DiskMountPoints() }
