package monetix

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"strings"
	"time"

	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/mlogger"
	"go.uber.org/zap"
)

const (
	outcomeAccepted     = "accepted"
	outcomeHTTPError    = "http_error"
	outcomeNetworkError = "network_error"
)

// sendCardPayout dispatches a PAN-based payout.
func (c *Client) sendCardPayout(ctx context.Context, req CardPayoutRequest) (*CardPayoutSendResult, error) {
	maskedPAN := MaskPAN(req.Card.PAN)
	return c.send(ctx, &req, "/v2/payment/card/payout",
		func() {
			c.logger.Info("Dispatching Monetix card payout",
				zap.String("payout_id", req.General.PaymentID),
				zap.Int64("amount_minor", req.Payment.Amount),
				zap.String("currency", req.Payment.Currency),
				zap.String("pan", maskedPAN),
			)
		},
		func(r *CardPayoutSendResult) {
			c.logger.Info("Monetix payout response",
				zap.String("payout_id", req.General.PaymentID),
				zap.Bool("accepted", r.Accepted),
				zap.Int("status_code", r.StatusCode),
				zap.String("provider_status", r.ProviderStatus),
				zap.String("provider_request_id", r.ProviderRequestID),
				zap.String("error_code", r.ErrorCode),
				zap.String("error_message", r.ErrorMessage),
			)
		})
}

// sendCardTokenPayout dispatches a token-based payout.
func (c *Client) sendCardTokenPayout(ctx context.Context, req CardTokenPayoutRequest) (*CardPayoutSendResult, error) {
	return c.send(ctx, &req, "/v2/payment/card/payout/token",
		func() {
			c.logger.Info("Dispatching Monetix card token payout",
				zap.String("payout_id", req.General.PaymentID),
				zap.Int64("amount_minor", req.Payment.Amount),
				zap.String("currency", req.Payment.Currency),
				zap.String("masked_pan", req.Token.MaskedPAN),
			)
		},
		func(r *CardPayoutSendResult) {
			c.logger.Info("Monetix token payout response",
				zap.String("payout_id", req.General.PaymentID),
				zap.Bool("accepted", r.Accepted),
				zap.Int("status_code", r.StatusCode),
				zap.String("provider_status", r.ProviderStatus),
				zap.String("provider_request_id", r.ProviderRequestID),
				zap.String("error_code", r.ErrorCode),
				zap.String("error_message", r.ErrorMessage),
			)
		})
}

// sendTokenization sends a tokenization request.
func (c *Client) sendTokenization(ctx context.Context, req CardTokenizeRequest) (*TokenizationResult, error) {
	if ctx == nil {
		ctx = context.Background()
	}
	if c == nil {
		return nil, merrors.Internal("monetix client not initialised")
	}
	if strings.TrimSpace(c.cfg.SecretKey) == "" {
		return nil, merrors.Internal("monetix secret key not configured")
	}
	if strings.TrimSpace(c.cfg.BaseURL) == "" {
		return nil, merrors.Internal("monetix base url not configured")
	}
	normalizeRequestExpiryYear(&req)

	req.General.Signature = ""
	signature, err := signPayload(req, c.cfg.SecretKey)
	if err != nil {
		return nil, merrors.Internal("failed to sign request: " + err.Error())
	}
	req.General.Signature = signature

	payload, err := json.Marshal(req)
	if err != nil {
		return nil, merrors.Internal("failed to marshal request payload: " + err.Error())
	}

	url := strings.TrimRight(c.cfg.BaseURL, "/") + "/v1/tokenize"
	httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
	if err != nil {
		return nil, merrors.Internal("failed to build request: " + err.Error())
	}
	httpReq.Header.Set("Content-Type", "application/json")
	httpReq.Header.Set("Accept", "application/json")

	c.logger.Info("Dispatching Monetix card tokenization",
		zap.String("request_id", req.General.PaymentID),
		zap.String("masked_pan", MaskPAN(req.Card.PAN)),
	)

	logRequestDeadline(c.logger, ctx, url)
	start := time.Now()
	resp, err := c.client.Do(httpReq)
	duration := time.Since(start)
	if err != nil {
		observeRequest(outcomeNetworkError, duration)
		fields := []zap.Field{
			zap.String("url", url),
			zap.Error(err),
		}
		if ctxErr := ctx.Err(); ctxErr != nil {
			fields = append(fields, zap.NamedError("ctx_error", ctxErr))
		}
		if deadline, ok := ctx.Deadline(); ok {
			fields = append(fields, zap.Time("deadline", deadline), zap.Duration("time_until_deadline", time.Until(deadline)))
		}
		c.logger.Warn("Monetix tokenization request failed", fields...)
		return nil, merrors.Internal("monetix tokenization request failed: " + err.Error())
	}
	defer func() {
		_ = resp.Body.Close()
	}()

	body, _ := io.ReadAll(resp.Body)
	outcome := outcomeAccepted
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		outcome = outcomeHTTPError
	}
	observeRequest(outcome, duration)

	result := &TokenizationResult{
		CardPayoutSendResult: CardPayoutSendResult{
			Accepted:   resp.StatusCode >= 200 && resp.StatusCode < 300,
			StatusCode: resp.StatusCode,
		},
	}

	var apiResp APIResponse
	if len(body) > 0 {
		if err := json.Unmarshal(body, &apiResp); err != nil {
			c.logger.Warn("Failed to decode Monetix tokenization response", zap.String("request_id", req.General.PaymentID), zap.Int("status_code", resp.StatusCode), zap.Error(err))
		} else {
			var tokenData struct {
				Token       string `json:"token"`
				MaskedPAN   string `json:"masked_pan"`
				ExpiryMonth string `json:"expiry_month"`
				ExpiryYear  string `json:"expiry_year"`
				CardBrand   string `json:"card_brand"`
			}
			_ = json.Unmarshal(body, &tokenData)
			result.Token = tokenData.Token
			result.MaskedPAN = tokenData.MaskedPAN
			result.ExpiryMonth = tokenData.ExpiryMonth
			result.ExpiryYear = tokenData.ExpiryYear
			result.CardBrand = tokenData.CardBrand
		}
	}

	result.ProviderRequestID = providerRequestID(apiResp)
	result.ProviderStatus = providerStatus(apiResp)

	errorCode, errorMessage := providerError(apiResp)
	if !result.Accepted || isProviderStatusError(result.ProviderStatus) {
		result.ErrorCode = errorCode
		if !result.Accepted && result.ErrorCode == "" {
			result.ErrorCode = http.StatusText(resp.StatusCode)
		}
		result.ErrorMessage = errorMessage
	}

	c.logger.Info("Monetix tokenization response",
		zap.String("request_id", req.General.PaymentID),
		zap.Bool("accepted", result.Accepted),
		zap.Int("status_code", resp.StatusCode),
		zap.String("provider_status", result.ProviderStatus),
		zap.String("provider_request_id", result.ProviderRequestID),
		zap.String("error_code", result.ErrorCode),
		zap.String("error_message", result.ErrorMessage),
	)

	return result, nil
}

func (c *Client) send(ctx context.Context, req any, path string, dispatchLog func(), responseLog func(*CardPayoutSendResult)) (*CardPayoutSendResult, error) {
	if ctx == nil {
		ctx = context.Background()
	}
	if c == nil {
		return nil, merrors.Internal("monetix client not initialised")
	}
	if strings.TrimSpace(c.cfg.SecretKey) == "" {
		return nil, merrors.Internal("monetix secret key not configured")
	}
	if strings.TrimSpace(c.cfg.BaseURL) == "" {
		return nil, merrors.Internal("monetix base url not configured")
	}
	normalizeRequestExpiryYear(req)

	setSignature, err := clearSignature(req)
	if err != nil {
		return nil, err
	}
	signature, err := signPayload(req, c.cfg.SecretKey)
	if err != nil {
		return nil, merrors.Internal("failed to sign request: " + err.Error())
	}
	setSignature(signature)

	payload, err := json.Marshal(req)
	if err != nil {
		return nil, merrors.Internal("failed to marshal request payload: " + err.Error())
	}

	url := strings.TrimRight(c.cfg.BaseURL, "/") + path
	httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
	if err != nil {
		return nil, merrors.Internal("failed to build request: " + err.Error())
	}
	httpReq.Header.Set("Content-Type", "application/json")
	httpReq.Header.Set("Accept", "application/json")

	if dispatchLog != nil {
		dispatchLog()
	}

	logRequestDeadline(c.logger, ctx, url)
	start := time.Now()
	resp, err := c.client.Do(httpReq)
	duration := time.Since(start)
	if err != nil {
		observeRequest(outcomeNetworkError, duration)
		fields := []zap.Field{
			zap.String("url", url),
			zap.Error(err),
		}
		if ctxErr := ctx.Err(); ctxErr != nil {
			fields = append(fields, zap.NamedError("ctx_error", ctxErr))
		}
		if deadline, ok := ctx.Deadline(); ok {
			fields = append(fields, zap.Time("deadline", deadline), zap.Duration("time_until_deadline", time.Until(deadline)))
		}
		c.logger.Warn("Monetix request failed", fields...)
		return nil, merrors.Internal("monetix request failed: " + err.Error())
	}
	defer func() {
		_ = resp.Body.Close()
	}()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		observeRequest(outcomeNetworkError, duration)
		c.logger.Warn("Failed to read Monetix response", zap.Int("status_code", resp.StatusCode), zap.Error(err))
		return nil, merrors.Internal("failed to read monetix response: " + err.Error())
	}
	outcome := outcomeAccepted
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		outcome = outcomeHTTPError
	}

	result := &CardPayoutSendResult{
		Accepted:   resp.StatusCode >= 200 && resp.StatusCode < 300,
		StatusCode: resp.StatusCode,
	}

	var apiResp APIResponse
	if len(body) > 0 {
		if err := json.Unmarshal(body, &apiResp); err != nil {
			observeRequest(outcomeHTTPError, duration)
			c.logger.Warn("Failed to decode Monetix response", zap.Int("status_code", resp.StatusCode), zap.Error(err))
			return nil, merrors.Internal("failed to decode monetix response: " + err.Error())
		}
	}

	result.ProviderRequestID = providerRequestID(apiResp)
	result.ProviderStatus = providerStatus(apiResp)

	errorCode, errorMessage := providerError(apiResp)
	if !result.Accepted || isProviderStatusError(result.ProviderStatus) {
		result.ErrorCode = errorCode
		if !result.Accepted && result.ErrorCode == "" {
			result.ErrorCode = http.StatusText(resp.StatusCode)
		}
		result.ErrorMessage = errorMessage
	}

	if responseLog != nil {
		responseLog(result)
	}
	observeRequest(outcome, duration)

	return result, nil
}

func normalizeExpiryYear(year int) int {
	if year > 0 && year < 100 {
		return year + 2000
	}
	return year
}

func providerRequestID(resp APIResponse) string {
	return firstNonEmpty(resp.Operation.RequestID, resp.RequestID)
}

func providerStatus(resp APIResponse) string {
	return firstNonEmpty(resp.Status, resp.Operation.Status)
}

func providerError(resp APIResponse) (code, message string) {
	return firstNonEmpty(resp.Code, resp.Operation.Code), firstNonEmpty(resp.Message, resp.Operation.Message)
}

func isProviderStatusError(status string) bool {
	return strings.EqualFold(strings.TrimSpace(status), "error")
}

func firstNonEmpty(values ...string) string {
	for _, value := range values {
		trimmed := strings.TrimSpace(value)
		if trimmed != "" {
			return trimmed
		}
	}
	return ""
}

func normalizeRequestExpiryYear(req any) {
	switch r := req.(type) {
	case *CardPayoutRequest:
		r.Card.Year = normalizeExpiryYear(r.Card.Year)
	case *CardTokenizeRequest:
		r.Card.Year = normalizeExpiryYear(r.Card.Year)
	}
}

func clearSignature(req any) (func(string), error) {
	switch r := req.(type) {
	case *CardPayoutRequest:
		r.General.Signature = ""
		return func(sig string) { r.General.Signature = sig }, nil
	case *CardTokenPayoutRequest:
		r.General.Signature = ""
		return func(sig string) { r.General.Signature = sig }, nil
	case *CardTokenizeRequest:
		r.General.Signature = ""
		return func(sig string) { r.General.Signature = sig }, nil
	default:
		return nil, merrors.Internal("unsupported monetix payload type for signing")
	}
}

func logRequestDeadline(logger mlogger.Logger, ctx context.Context, url string) {
	if ctx == nil {
		logger.Info("Monetix request context is nil", zap.String("url", url))
		return
	}
	deadline, ok := ctx.Deadline()
	if !ok {
		logger.Info("Monetix request context has no deadline", zap.String("url", url))
		return
	}
	logger.Debug("Monetix request context deadline",
		zap.String("url", url),
		zap.Time("deadline", deadline),
		zap.Duration("time_until_deadline", time.Until(deadline)),
	)
}
