package order

import (
	"testing"
	"time"

	modelorder "github.com/perfect-panel/server/internal/model/order"
	modeluser "github.com/perfect-panel/server/internal/model/user"
)

func TestOrderStatusName(t *testing.T) {
	tests := map[uint8]string{
		1: "pending",
		2: "paid",
		3: "closed",
		4: "failed",
		5: "finished",
		6: "refunded",
		7: "unknown",
	}

	for input, want := range tests {
		if got := orderStatusName(input); got != want {
			t.Fatalf("status %d: got %q want %q", input, got, want)
		}
	}
}

func TestBuildRefundAuditLog(t *testing.T) {
	logic := &RefundOrderLogic{}
	now := time.Unix(1710000000, 0)
	expireBefore := now.Add(24 * time.Hour)
	expireAfter := now.Add(-time.Second)
	operator := &modeluser.User{
		Id: 100,
		AuthMethods: []modeluser.AuthMethods{
			{AuthIdentifier: "admin@example.com"},
		},
	}
	orderInfo := &modelorder.Order{Id: 10, OrderNo: "ORD-1", Status: orderStatusRefunded}
	userSub := &modeluser.Subscribe{Id: 20, UserId: 30, Status: 3, ExpireTime: expireAfter}
	referer := &modeluser.User{Id: 40}

	got, err := logic.buildRefundAuditLog(
		operator,
		orderInfo,
		userSub,
		referer,
		500,
		"manual refund",
		5,
		1,
		expireBefore,
		900,
		400,
		now,
	)
	if err != nil {
		t.Fatalf("buildRefundAuditLog error: %v", err)
	}
	if got.OrderId != 10 || got.OrderNo != "ORD-1" {
		t.Fatalf("unexpected order info: %+v", got)
	}
	if got.OperatorUserId != 100 || got.OperatorAuthIdentifier != "admin@example.com" {
		t.Fatalf("unexpected operator info: %+v", got)
	}
	if got.TargetUserId != 30 || got.UserSubscribeId != 20 {
		t.Fatalf("unexpected subscription info: %+v", got)
	}
	if got.RefererUserId != 40 || got.CommissionAmount != 500 {
		t.Fatalf("unexpected commission info: %+v", got)
	}
	if got.OrderStatusBefore != 5 || got.OrderStatusAfter != orderStatusRefunded {
		t.Fatalf("unexpected order status: %+v", got)
	}
	if got.SubscribeStatusBefore != 1 || got.SubscribeStatusAfter != 3 {
		t.Fatalf("unexpected subscribe status: %+v", got)
	}
	if got.SubscribeExpireBefore != expireBefore.UnixMilli() || got.SubscribeExpireAfter != expireAfter.UnixMilli() {
		t.Fatalf("unexpected expire transition: %+v", got)
	}
	if got.CommissionBefore != 900 || got.CommissionAfter != 400 {
		t.Fatalf("unexpected commission transition: %+v", got)
	}
}
