package service

import (
	"testing"

	"github.com/user-management-system/internal/domain"
)

// =============================================================================
// Login Log Helper Functions Tests
// =============================================================================

func TestLoginTypeLabel(t *testing.T) {
	tests := []struct {
		name     string
		val      int
		expected string
	}{
		{"password login", 1, "密码登录"},
		{"email code login", 2, "邮箱验证码"},
		{"phone code login", 3, "手机验证码"},
		{"oauth login", 4, "OAuth"},
		{"unknown type", 99, "未知"},
		{"zero", 0, "未知"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := loginTypeLabel(tt.val)
			if result != tt.expected {
				t.Errorf("loginTypeLabel(%d) = %q, want %q", tt.val, result, tt.expected)
			}
		})
	}
}

func TestLoginStatusLabel(t *testing.T) {
	tests := []struct {
		name     string
		status   int
		expected string
	}{
		{"success", 1, "成功"},
		{"failure", 0, "失败"},
		{"other value", 2, "失败"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := loginStatusLabel(tt.status)
			if result != tt.expected {
				t.Errorf("loginStatusLabel(%d) = %q, want %q", tt.status, result, tt.expected)
			}
		})
	}
}

func TestDerefInt64(t *testing.T) {
	t.Run("nil pointer returns 0", func(t *testing.T) {
		result := derefInt64(nil)
		if result != 0 {
			t.Errorf("Expected 0 for nil, got %d", result)
		}
	})

	t.Run("non-nil pointer returns value", func(t *testing.T) {
		val := int64(12345)
		result := derefInt64(&val)
		if result != 12345 {
			t.Errorf("Expected 12345, got %d", result)
		}
	})
}

func TestBuildLoginLogCSVExport(t *testing.T) {
	t.Run("empty logs", func(t *testing.T) {
		data, err := buildLoginLogCSVExport([]*domain.LoginLog{})
		if err != nil {
			t.Fatalf("buildLoginLogCSVExport failed: %v", err)
		}
		if len(data) == 0 {
			t.Error("Expected non-empty CSV output")
		}
	})

	t.Run("with logs", func(t *testing.T) {
		userID := int64(1)
		logs := []*domain.LoginLog{
			{ID: 1, UserID: &userID, LoginType: 1, DeviceID: "device1", IP: "192.168.1.1", Location: "Beijing", Status: 1},
			{ID: 2, UserID: nil, LoginType: 2, DeviceID: "device2", IP: "10.0.0.1", Location: "Shanghai", Status: 0, FailReason: "Invalid code"},
		}
		data, err := buildLoginLogCSVExport(logs)
		if err != nil {
			t.Fatalf("buildLoginLogCSVExport failed: %v", err)
		}
		if len(data) == 0 {
			t.Error("Expected non-empty CSV output")
		}
	})
}
