package payment

import (
	"testing"
	"time"

	"hfb_sys/backend/internal/model"
	"hfb_sys/backend/internal/timeutil"

	"gorm.io/datatypes"
)

func TestCanReuseOrderPaymentRejectsTerminalAndOldChannel(t *testing.T) {
	runtimeConfig := runtimePaymentConfig{
		Provider:   "lakala",
		MerchantID: "M2",
	}

	cases := []struct {
		name    string
		payment model.PaymentOrder
		want    bool
	}{
		{
			name:    "同商户支付中可复用",
			payment: model.PaymentOrder{Status: "paying", Provider: "lakala", MerchantID: "M2"},
			want:    true,
		},
		{
			name:    "已支付保持幂等",
			payment: model.PaymentOrder{Status: "paid", Provider: "leshua", MerchantID: "M1"},
			want:    true,
		},
		{
			name:    "失败支付单不复用",
			payment: model.PaymentOrder{Status: "failed", Provider: "lakala", MerchantID: "M2"},
			want:    false,
		},
		{
			name:    "关闭支付单不复用",
			payment: model.PaymentOrder{Status: "closed", Provider: "lakala", MerchantID: "M2"},
			want:    false,
		},
		{
			name:    "旧渠道支付单不复用",
			payment: model.PaymentOrder{Status: "paying", Provider: "leshua", MerchantID: "M1"},
			want:    false,
		},
		{
			name:    "旧商户支付单不复用",
			payment: model.PaymentOrder{Status: "paying", Provider: "lakala", MerchantID: "M1"},
			want:    false,
		},
	}

	for _, tt := range cases {
		t.Run(tt.name, func(t *testing.T) {
			if got := canReuseOrderPayment(tt.payment, runtimeConfig); got != tt.want {
				t.Fatalf("canReuseOrderPayment() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestNewOrderPaymentUsesPaymentNoAsThirdOrderID(t *testing.T) {
	order := model.RentalOrder{
		ID:       11,
		OrderNo:  "ORD123",
		RenterID: 7,
	}
	runtimeConfig := runtimePaymentConfig{
		Provider:   "lakala",
		MerchantID: "M2",
		PayWay:     "ZFBZF",
		JSPayFlag:  "2",
	}

	payment, err := newOrderPayment(order, 100, StartPaymentRequest{}, runtimeConfig)
	if err != nil {
		t.Fatalf("newOrderPayment() error = %v", err)
	}
	if payment.ThirdOrderID != payment.PaymentNo {
		t.Fatalf("ThirdOrderID = %q, want PaymentNo %q", payment.ThirdOrderID, payment.PaymentNo)
	}
	if payment.ThirdOrderID == order.OrderNo {
		t.Fatalf("ThirdOrderID should not reuse order no %q", order.OrderNo)
	}
	if payment.OrderNo != order.OrderNo || payment.OrderID != order.ID || payment.UserID != order.RenterID {
		t.Fatalf("payment order fields mismatch: %+v", payment)
	}
}

func TestCanReuseOrderPaymentRejectsExpiredCashier(t *testing.T) {
	runtimeConfig := runtimePaymentConfig{
		Provider:   "lakala",
		MerchantID: "M2",
	}
	expiredPayment := model.PaymentOrder{
		Status:     "paying",
		Provider:   "lakala",
		MerchantID: "M2",
		RawRequest: datatypes.JSON([]byte(`{"order_efficient_time":"20000101000000"}`)),
	}
	if canReuseOrderPayment(expiredPayment, runtimeConfig) {
		t.Fatal("canReuseOrderPayment() = true, want false for expired cashier")
	}

	activePayment := expiredPayment
	activePayment.RawRequest = datatypes.JSON([]byte(`{"order_efficient_time":"20990101000000"}`))
	if !canReuseOrderPayment(activePayment, runtimeConfig) {
		t.Fatal("canReuseOrderPayment() = false, want true for active cashier")
	}
}

func TestParseChannelTimeUsesShanghaiWhenLocalIsUTC(t *testing.T) {
	oldLocal := time.Local
	time.Local = time.UTC
	defer func() {
		time.Local = oldLocal
	}()

	parsed := parseChannelTime("20260607202700")
	if parsed == nil {
		t.Fatal("parseChannelTime() = nil")
	}
	got := parsed.In(timeutil.ShanghaiLocation()).Format("20060102150405")
	if got != "20260607202700" {
		t.Fatalf("parseChannelTime() = %s, want 20260607202700 in Asia/Shanghai", got)
	}
}

func TestRefundOriginProviderOrderIDUsesLakalaTradeNo(t *testing.T) {
	payment := model.PaymentOrder{
		Provider:        "lakala",
		ProviderOrderID: "26060811012001101011735013210",
		RawResponse: datatypes.JSON([]byte(`{
			"pay_order_no": "26060811012001101011735013210",
			"order_trade_info_list": "[{\"trade_no\":\"20260608110113230266224452004512\",\"pay_order_no\":\"26060811012001101011735013210\"}]"
		}`)),
	}

	got := refundOriginProviderOrderID(payment)
	if got != "20260608110113230266224452004512" {
		t.Fatalf("refundOriginProviderOrderID() = %q, want trade_no", got)
	}
}

func TestRefundOriginProviderOrderIDFallsBackToProviderOrderID(t *testing.T) {
	payment := model.PaymentOrder{
		Provider:        "lakala",
		ProviderOrderID: "26060811012001101011735013210",
		RawResponse:     datatypes.JSON([]byte(`{"pay_order_no":"26060811012001101011735013210"}`)),
	}

	got := refundOriginProviderOrderID(payment)
	if got != payment.ProviderOrderID {
		t.Fatalf("refundOriginProviderOrderID() = %q, want fallback %q", got, payment.ProviderOrderID)
	}
}

func TestRefundQueryRequestUsesOriginalPaymentAndMerchantRefundID(t *testing.T) {
	original := model.PaymentOrder{
		ThirdOrderID:    "PAY202606140001",
		ProviderOrderID: "PROVIDER-PAY-ID",
	}
	refund := model.PaymentOrder{
		ThirdOrderID:    "REF202606140001",
		ProviderOrderID: "PROVIDER-REFUND-ID",
	}

	req := refundQueryRequest(refund, original)
	if req.ThirdOrderID != original.ThirdOrderID {
		t.Fatalf("ThirdOrderID = %q, want original payment third order id %q", req.ThirdOrderID, original.ThirdOrderID)
	}
	if req.MerchantRefundID != refund.ThirdOrderID {
		t.Fatalf("MerchantRefundID = %q, want refund third order id %q", req.MerchantRefundID, refund.ThirdOrderID)
	}
	if req.ProviderRefundID != refund.ProviderOrderID {
		t.Fatalf("ProviderRefundID = %q, want refund provider order id %q", req.ProviderRefundID, refund.ProviderOrderID)
	}
}
