package quote_persistence_service

import (
	"github.com/tech/sendico/payments/storage/model"
	"github.com/tech/sendico/pkg/merrors"
	quotationv2 "github.com/tech/sendico/pkg/proto/payments/quotation/v2"
)

func mapStatusInput(input *StatusInput) (*model.QuoteStatusV2, error) {
	if input == nil {
		return nil, merrors.InvalidArgument("status is required")
	}

	if input.State == quotationv2.QuoteState_QUOTE_STATE_UNSPECIFIED {
		return nil, merrors.InvalidArgument("status.state is required")
	}
	if input.State == quotationv2.QuoteState_QUOTE_STATE_BLOCKED {
		if input.BlockReason == quotationv2.QuoteBlockReason_QUOTE_BLOCK_REASON_UNSPECIFIED {
			return nil, merrors.InvalidArgument("status.block_reason is required for blocked quote")
		}
	} else if input.BlockReason != quotationv2.QuoteBlockReason_QUOTE_BLOCK_REASON_UNSPECIFIED {
		return nil, merrors.InvalidArgument("status.block_reason is only valid for blocked quote")
	}

	return &model.QuoteStatusV2{
		State:       mapQuoteState(input.State),
		BlockReason: mapQuoteBlockReason(input.BlockReason),
	}, nil
}

func mapQuoteState(state quotationv2.QuoteState) model.QuoteState {
	switch state {
	case quotationv2.QuoteState_QUOTE_STATE_INDICATIVE:
		return model.QuoteStateIndicative
	case quotationv2.QuoteState_QUOTE_STATE_EXECUTABLE:
		return model.QuoteStateExecutable
	case quotationv2.QuoteState_QUOTE_STATE_BLOCKED:
		return model.QuoteStateBlocked
	case quotationv2.QuoteState_QUOTE_STATE_EXPIRED:
		return model.QuoteStateExpired
	default:
		return model.QuoteStateUnspecified
	}
}

func mapQuoteBlockReason(reason quotationv2.QuoteBlockReason) model.QuoteBlockReason {
	switch reason {
	case quotationv2.QuoteBlockReason_QUOTE_BLOCK_REASON_ROUTE_UNAVAILABLE:
		return model.QuoteBlockReasonRouteUnavailable
	case quotationv2.QuoteBlockReason_QUOTE_BLOCK_REASON_LIMIT_BLOCKED:
		return model.QuoteBlockReasonLimitBlocked
	case quotationv2.QuoteBlockReason_QUOTE_BLOCK_REASON_RISK_BLOCKED:
		return model.QuoteBlockReasonRiskBlocked
	case quotationv2.QuoteBlockReason_QUOTE_BLOCK_REASON_INSUFFICIENT_LIQUIDITY:
		return model.QuoteBlockReasonInsufficientLiquidity
	case quotationv2.QuoteBlockReason_QUOTE_BLOCK_REASON_PRICE_STALE:
		return model.QuoteBlockReasonPriceStale
	case quotationv2.QuoteBlockReason_QUOTE_BLOCK_REASON_AMOUNT_TOO_SMALL:
		return model.QuoteBlockReasonAmountTooSmall
	case quotationv2.QuoteBlockReason_QUOTE_BLOCK_REASON_AMOUNT_TOO_LARGE:
		return model.QuoteBlockReasonAmountTooLarge
	default:
		return model.QuoteBlockReasonUnspecified
	}
}
