package mission

import (
	"sort"
	"strings"

	sharedconst "wucher/internal/shared/const"
)

const (
	StatusDraft      = "draft"
	StatusInProgress = "in_progress"
	StatusCompleted  = "completed"
)

const (
	FormKeyFlightData  = "flight_data"
	FormKeyPatientData = "patient_data"
)

var missionTypeForms = map[string][]string{
	sharedconst.MissionTypeHEMS: []string{FormKeyFlightData, FormKeyPatientData},
	sharedconst.MissionTypeCAT:  []string{FormKeyFlightData},
	sharedconst.MissionTypeSPO:  []string{FormKeyFlightData},
	sharedconst.MissionTypeNCO:  []string{FormKeyFlightData},
}

type FormFacts map[string]string

type FormStatus struct {
	Key    string
	Status string
}

func BuildForms(missionType string, facts FormFacts) []FormStatus {
	keys := missionFormsForType(missionType)
	if len(keys) == 0 {
		keys = sortedFactKeys(facts)
	}
	out := make([]FormStatus, 0, len(keys))
	if len(keys) == 0 {
		return out
	}

	for _, key := range keys {
		out = append(out, formStatus(key, facts[key]))
	}
	return out
}

func missionFormsForType(missionType string) []string {
	missionType = strings.ToUpper(strings.TrimSpace(missionType))
	if forms, ok := missionTypeForms[missionType]; ok && len(forms) > 0 {
		out := make([]string, len(forms))
		copy(out, forms)
		return out
	}

	return nil
}

func sortedFactKeys(facts FormFacts) []string {
	keys := make([]string, 0, len(facts))
	for key := range facts {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	return keys
}

// ComputeStatus derives the mission state from its forms so new forms can be
// added later without reworking mission-level branching.
func ComputeStatus(forms []FormStatus) string {
	if len(forms) == 0 {
		return StatusDraft
	}

	completed := 0
	inProgress := 0
	for i := range forms {
		switch forms[i].Status {
		case StatusCompleted:
			completed++
		case StatusInProgress:
			inProgress++
		}
	}

	switch {
	case completed == 0:
		if inProgress > 0 {
			return StatusInProgress
		}
		return StatusDraft
	case completed == len(forms):
		return StatusCompleted
	default:
		return StatusInProgress
	}
}

func formStatus(key, status string) FormStatus {
	return FormStatus{Key: key, Status: normalizeFormStatus(status)}
}

func normalizeFormStatus(status string) string {
	switch strings.ToLower(strings.TrimSpace(status)) {
	case StatusCompleted:
		return StatusCompleted
	case StatusInProgress:
		return StatusInProgress
	default:
		return StatusDraft
	}
}
