package settings

import (
	"context"

	"apps/backend/internal/middleware"
	"apps/backend/internal/module/member/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SavePlacementLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSavePlacementLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SavePlacementLogic {
	return &SavePlacementLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}

func (l *SavePlacementLogic) SavePlacement(req *types.SavePlacementReq) (resp *types.PlacementSettingsData, err error) {
	uid, _ := middleware.UIDFrom(l.ctx)
	st, err := l.svcCtx.Members.GetSettings(l.ctx, uid)
	if err != nil {
		return nil, err
	}
	if st == nil {
		st = domain.DefaultSettings(uid)
	}
	if req.ExpandStrategy != "" && req.ExpandStrategy != "brave" {
		st.ExpandStrategy = req.ExpandStrategy
	}
	if req.DevModeEnabled != nil {
		st.DevModeEnabled = *req.DevModeEnabled
	}
	if req.ExaApiKey != "" {
		st.ExaAPIKey = req.ExaApiKey
		st.ExaAPIKeyConfigured = true
	}
	if req.ExaApiKeyConfigured != nil && !*req.ExaApiKeyConfigured {
		st.ExaAPIKey = ""
		st.ExaAPIKeyConfigured = false
	}
	if err := l.svcCtx.Members.SaveSettings(l.ctx, uid, st); err != nil {
		return nil, err
	}
	return NewGetPlacementLogic(l.ctx, l.svcCtx).GetPlacement()
}
