package system

import (
	"context"

	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/tool"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
)

type GetRegisterConfigLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetRegisterConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRegisterConfigLogic {
	return &GetRegisterConfigLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetRegisterConfigLogic) GetRegisterConfig() (*types.RegisterConfig, error) {
	resp := &types.RegisterConfig{
		StopRegister:              l.svcCtx.Config.Register.StopRegister,
		EnableTrial:               l.svcCtx.Config.Register.EnableTrial,
		EnableTrialEmailWhitelist: l.svcCtx.Config.Register.EnableTrialEmailWhitelist,
		TrialSubscribe:            l.svcCtx.Config.Register.TrialSubscribe,
		TrialTime:                 l.svcCtx.Config.Register.TrialTime,
		TrialTimeUnit:             l.svcCtx.Config.Register.TrialTimeUnit,
		TrialEmailDomainWhitelist: l.svcCtx.Config.Register.TrialEmailDomainWhitelist,
		EnableIpRegisterLimit:     l.svcCtx.Config.Register.EnableIpRegisterLimit,
		IpRegisterLimit:           l.svcCtx.Config.Register.IpRegisterLimit,
		IpRegisterLimitDuration:   l.svcCtx.Config.Register.IpRegisterLimitDuration,
		DeviceLimit:               l.svcCtx.Config.Register.DeviceLimit,
	}

	// get register config from database
	configs, err := l.svcCtx.SystemModel.GetRegisterConfig(l.ctx)
	if err != nil {
		l.Errorw("[GetRegisterConfig] Database query error", logger.Field("error", err.Error()))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get register config error: %v", err.Error())
	}

	// reflect to response
	tool.SystemConfigSliceReflectToStruct(configs, resp)
	return resp, nil
}
