package radar

import (
	"context"
	"fmt"

	"apps/backend/internal/logic/radarmap"
	"apps/backend/internal/module/radar/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *UpdateDemandMapLogic) UpdateDemandMap(req *types.UpdateDemandMapReq) (resp *types.DemandMapPublic, err error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	if req == nil || req.ProductId == "" {
		return nil, fmt.Errorf("%w: product id required", domain.ErrValidation)
	}
	if req.ExpectedMapVersion < 1 {
		return nil, fmt.Errorf("%w: expected map version required", domain.ErrValidation)
	}
	current, err := l.svcCtx.Radar.GetDemandMap(l.ctx, uid, req.ProductId)
	if err != nil {
		return nil, err
	}
	phrase := func(in []types.DemandMapPhrase) []domain.DemandMapPhrase {
		out := make([]domain.DemandMapPhrase, 0, len(in))
		for _, p := range in {
			out = append(out, domain.DemandMapPhrase{Text: p.Text, Kind: p.Kind, BasisKind: p.BasisKind, BasisText: p.BasisText, Origin: p.Origin, Enabled: p.Enabled})
		}
		return out
	}
	value := &domain.DemandMap{
		OwnerUID: uid, ProductID: req.ProductId, DemandInputVersion: current.DemandInputVersion,
		MapVersion: current.MapVersion, State: demandMapState(req),
		PainPhrases: phrase(req.PainPhrases), ScenarioPhrases: phrase(req.ScenarioPhrases), DesiredOutcomes: phrase(req.DesiredOutcomes),
		SolutionSignals: phrase(req.SolutionSignals), ExclusionSignals: phrase(req.ExclusionSignals), CustomPhrases: phrase(req.CustomPhrases),
		SourceBasis: append([]string(nil), current.SourceBasis...), AIEnrichedAt: current.AIEnrichedAt,
	}
	updated, err := l.svcCtx.Radar.UpdateDemandMap(l.ctx, uid, value, req.ExpectedMapVersion)
	if err != nil {
		return nil, err
	}
	return radarmap.DemandMap(updated), nil
}

func demandMapState(req *types.UpdateDemandMapReq) string {
	if len(req.PainPhrases) > 0 && len(req.ScenarioPhrases) > 0 && len(req.SolutionSignals) > 0 {
		return "ready"
	}
	return "incomplete"
}
