package domain

import (
	"strings"
)

type DemandMapPhrase struct {
	Text      string `bson:"text" json:"text"`
	Kind      string `bson:"kind" json:"kind"`
	BasisKind string `bson:"basis_kind,omitempty" json:"basis_kind,omitempty"`
	BasisText string `bson:"basis_text,omitempty" json:"basis_text,omitempty"`
	Origin    string `bson:"origin" json:"origin"`
	Enabled   bool   `bson:"enabled" json:"enabled"`
}

type DemandMap struct {
	ID                  string             `bson:"_id" json:"id"`
	OwnerUID            int64              `bson:"owner_uid" json:"owner_uid"`
	ProductID           string             `bson:"product_id" json:"product_id"`
	DemandInputVersion  string             `bson:"demand_input_version" json:"demand_input_version"`
	MapVersion          int64              `bson:"map_version" json:"map_version"`
	State               string             `bson:"state" json:"state"`
	PainPhrases         []DemandMapPhrase  `bson:"pain_phrases" json:"pain_phrases"`
	ScenarioPhrases     []DemandMapPhrase  `bson:"scenario_phrases" json:"scenario_phrases"`
	DesiredOutcomes     []DemandMapPhrase  `bson:"desired_outcomes" json:"desired_outcomes"`
	SolutionSignals     []DemandMapPhrase  `bson:"solution_signals" json:"solution_signals"`
	ExclusionSignals    []DemandMapPhrase  `bson:"exclusion_signals" json:"exclusion_signals"`
	SourceBasis         []string           `bson:"source_basis" json:"source_basis"`
	CustomPhrases       []DemandMapPhrase  `bson:"custom_phrases" json:"custom_phrases"`
	AIEnrichedAt        int64              `bson:"ai_enriched_at,omitempty" json:"ai_enriched_at,omitempty"`
	UpdatedAt           int64              `bson:"updated_at" json:"updated_at"`
}

func (m *DemandMap) Normalize() error {
	if m.OwnerUID <= 0 || strings.TrimSpace(m.ProductID) == "" || strings.TrimSpace(m.DemandInputVersion) == "" {
		return ErrValidation
	}
	if m.MapVersion < 1 {
		m.MapVersion = 1
	}
	if m.State != "ready" && m.State != "incomplete" && m.State != "stale" {
		return ErrValidation
	}
	for i := range m.PainPhrases {
		normalizeDemandPhrase(&m.PainPhrases[i])
	}
	for i := range m.ScenarioPhrases {
		normalizeDemandPhrase(&m.ScenarioPhrases[i])
	}
	for i := range m.DesiredOutcomes {
		normalizeDemandPhrase(&m.DesiredOutcomes[i])
	}
	for i := range m.SolutionSignals {
		normalizeDemandPhrase(&m.SolutionSignals[i])
	}
	for i := range m.ExclusionSignals {
		normalizeDemandPhrase(&m.ExclusionSignals[i])
	}
	for i := range m.CustomPhrases {
		normalizeDemandPhrase(&m.CustomPhrases[i])
	}
	return nil
}

func normalizeDemandPhrase(p *DemandMapPhrase) {
	p.Text = strings.TrimSpace(p.Text)
	p.Kind = strings.TrimSpace(p.Kind)
	p.BasisKind = strings.TrimSpace(p.BasisKind)
	p.BasisText = strings.TrimSpace(p.BasisText)
	p.Origin = strings.TrimSpace(p.Origin)
}
