package oobs

import (
	"strings"

	"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrationv2/agg"
)

const (
	defaultTimelineLimit int32 = 100
	maxTimelineLimit     int32 = 1000
)

func normalizePaymentEvent(event PaymentEvent) (PaymentEvent, bool) {
	switch strings.ToLower(strings.TrimSpace(string(event))) {
	case string(PaymentEventCreated):
		return PaymentEventCreated, true
	case string(PaymentEventStateChanged):
		return PaymentEventStateChanged, true
	case string(PaymentEventNeedsAttention):
		return PaymentEventNeedsAttention, true
	case string(PaymentEventSettled):
		return PaymentEventSettled, true
	case string(PaymentEventFailed):
		return PaymentEventFailed, true
	default:
		return "", false
	}
}

func normalizeStepEvent(event StepEvent) (StepEvent, bool) {
	switch strings.ToLower(strings.TrimSpace(string(event))) {
	case string(StepEventScheduled):
		return StepEventScheduled, true
	case string(StepEventStarted):
		return StepEventStarted, true
	case string(StepEventCompleted):
		return StepEventCompleted, true
	case string(StepEventFailed):
		return StepEventFailed, true
	case string(StepEventSkipped):
		return StepEventSkipped, true
	case string(StepEventBlocked):
		return StepEventBlocked, true
	default:
		return "", false
	}
}

func normalizeExternalSource(source ExternalSource) (ExternalSource, bool) {
	switch strings.ToLower(strings.TrimSpace(string(source))) {
	case string(ExternalSourceGateway):
		return ExternalSourceGateway, true
	case string(ExternalSourceLedger):
		return ExternalSourceLedger, true
	case string(ExternalSourceCard):
		return ExternalSourceCard, true
	default:
		return "", false
	}
}

func normalizeAggregateState(state agg.State) (agg.State, bool) {
	switch strings.ToLower(strings.TrimSpace(string(state))) {
	case string(agg.StateCreated):
		return agg.StateCreated, true
	case string(agg.StateExecuting):
		return agg.StateExecuting, true
	case string(agg.StateNeedsAttention):
		return agg.StateNeedsAttention, true
	case string(agg.StateSettled):
		return agg.StateSettled, true
	case string(agg.StateFailed):
		return agg.StateFailed, true
	default:
		return agg.StateUnspecified, false
	}
}

func normalizeStepState(state agg.StepState) (agg.StepState, bool) {
	switch strings.ToLower(strings.TrimSpace(string(state))) {
	case string(agg.StepStatePending):
		return agg.StepStatePending, true
	case string(agg.StepStateRunning):
		return agg.StepStateRunning, true
	case string(agg.StepStateCompleted):
		return agg.StepStateCompleted, true
	case string(agg.StepStateFailed):
		return agg.StepStateFailed, true
	case string(agg.StepStateNeedsAttention):
		return agg.StepStateNeedsAttention, true
	case string(agg.StepStateSkipped):
		return agg.StepStateSkipped, true
	default:
		return agg.StepStateUnspecified, false
	}
}

func normalizeLimit(limit int32) int32 {
	if limit <= 0 {
		return defaultTimelineLimit
	}
	if limit > maxTimelineLimit {
		return maxTimelineLimit
	}
	return limit
}
