package flightdata

import (
	"strings"

	sharedconst "wucher/internal/shared/const"
)

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

// IsComplete reports whether the persisted flight-data status is complete.
func IsComplete(row *FlightData) bool {
	if row == nil {
		return false
	}

	return strings.EqualFold(strings.TrimSpace(row.Status), StatusCompleted)
}

func DeriveStatus(row *FlightData, details *SPODetails) string {
	if !isBaseComplete(row) {
		return StatusInProgress
	}

	switch missionType(row) {
	case sharedconst.MissionTypeCAT, sharedconst.MissionTypeNCO, sharedconst.MissionTypeSPO:
		return StatusCompleted
	case sharedconst.MissionTypeHEMS:
		return StatusCompleted
	}

	return StatusInProgress
}

func hasExactlyOneLocation(a, b []byte) bool {
	hasA := len(a) == 16
	hasB := len(b) == 16
	return hasA != hasB
}

func missionType(row *FlightData) string {
	if row == nil || row.Mission == nil {
		return ""
	}
	return strings.ToUpper(strings.TrimSpace(row.Mission.Type))
}

func isBaseComplete(row *FlightData) bool {
	if row == nil {
		return false
	}

	requiresRotorBrakeCycle := true
	switch missionType(row) {
	case sharedconst.MissionTypeCAT, sharedconst.MissionTypeNCO, sharedconst.MissionTypeSPO:
		requiresRotorBrakeCycle = false
	}

	return len(row.MissionID) == 16 &&
		hasExactlyOneLocation(row.FromICAOID, row.FromHospitalID) &&
		hasExactlyOneLocation(row.ToICAOID, row.ToHospitalID) &&
		!row.FlightTakeOff.IsZero() &&
		!row.FlightLanding.IsZero() &&
		row.FlightDuration > 0 &&
		row.LandingCount > 0 &&
		(!requiresRotorBrakeCycle || row.RotorBrakeCycle > 0)
}

func isHESLOComplete(details SPOHESLODetails) bool {
	if len(details.Flights) == 0 || len(details.Slings) == 0 {
		return false
	}
	for i := range details.Flights {
		if details.Flights[i].ROT <= 0 || len(details.Flights[i].FuelTruckID) != 16 || len(details.Flights[i].LoggingSlingID) != 16 {
			return false
		}
	}
	for i := range details.Slings {
		if len(details.Slings[i].HESLOFlightID) != 16 || len(details.Slings[i].SlingID) != 16 {
			return false
		}
	}
	return true
}

func isLoggingComplete(details SPOLoggingDetails) bool {
	if len(details.Slings) == 0 {
		return false
	}
	for i := range details.Slings {
		if len(details.Slings[i].SlingID) != 16 {
			return false
		}
	}
	return true
}

func isHECComplete(details SPOHECDetails) bool {
	if len(details.Flights) == 0 || len(details.Slings) == 0 || len(details.Loads) == 0 {
		return false
	}
	for i := range details.Flights {
		if details.Flights[i].ROT <= 0 || details.Flights[i].HECCycle <= 0 || len(details.Flights[i].EquipmentID) != 16 {
			return false
		}
	}
	for i := range details.Slings {
		if len(details.Slings[i].SlingID) != 16 {
			return false
		}
	}
	for i := range details.Loads {
		if strings.TrimSpace(details.Loads[i].LoadCategory) == "" || details.Loads[i].Quantity <= 0 {
			return false
		}
	}
	return true
}
