package gateway

import (
	"context"

	"github.com/tech/sendico/gateway/tgsettle/storage/model"
	paymentgateway "github.com/tech/sendico/pkg/messaging/notifications/paymentgateway"
	pmodel "github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mservice"
	"github.com/tech/sendico/pkg/mutil/mzap"
	"github.com/tech/sendico/pkg/payments/rail"
	"go.uber.org/zap"
)

func isFinalStatus(t *model.PaymentRecord) bool {
	switch t.Status {
	case model.PaymentStatusFailed, model.PaymentStatusSuccess, model.PaymentStatusCancelled:
		return true
	default:
		return false
	}
}

func toOpStatus(t *model.PaymentRecord) rail.OperationResult {
	switch t.Status {
	case model.PaymentStatusFailed:
		return rail.OperationResultFailed
	case model.PaymentStatusSuccess:
		return rail.OperationResultSuccess
	case model.PaymentStatusCancelled:
		return rail.OperationResultCancelled
	default:
		panic("unexpected transfer status")
	}
}

func (s *Service) updateTransferStatus(ctx context.Context, record *model.PaymentRecord) error {
	if err := s.repo.Payments().Upsert(ctx, record); err != nil {
		s.logger.Warn("Failed to update transfer status", zap.String("payment_ref", record.PaymentIntentID), zap.String("status", string(record.Status)), zap.Error(err))
		return err
	}
	if isFinalStatus(record) {
		s.emitTransferStatusEvent(ctx, record)
	}
	return nil
}

func (s *Service) emitTransferStatusEvent(_ context.Context, record *model.PaymentRecord) {
	if s == nil || s.producer == nil || record == nil {
		return
	}

	exec := pmodel.PaymentGatewayExecution{
		PaymentIntentID: record.PaymentIntentID,
		IdempotencyKey:  record.IdempotencyKey,
		ExecutedMoney:   record.ExecutedMoney,
		PaymentRef:      record.PaymentRef,
		Status:          toOpStatus(record),
		OperationRef:    record.OperationRef,
		Error:           record.FailureReason,
		TransferRef:     record.ID.Hex(),
	}
	env := paymentgateway.PaymentGatewayExecution(mservice.MntxGateway, &exec)
	if err := s.producer.SendMessage(env); err != nil {
		s.logger.Warn("Failed to publish transfer status event", zap.Error(err), mzap.ObjRef("transfer_ref", record.ID))
	}
}
