package appuser

import (
	"context"
	"strings"
	"testing"
)

func TestBanListWhereSQLBuildsTargetKeywordFilter(t *testing.T) {
	whereSQL, args := banListWhereSQL(context.Background(), banListQuery{
		TargetKeyword: "10086",
	}, nil)

	for _, fragment := range []string{
		"target.status IN ('banned', 'disabled')",
		"CAST(target.user_id AS CHAR) LIKE ?",
		"target.current_display_user_id LIKE ?",
		"target.default_display_user_id LIKE ?",
		"target.username LIKE ?",
		"pretty_display_user_id_leases lease",
	} {
		if !strings.Contains(whereSQL, fragment) {
			t.Fatalf("where sql missing %q: %s", fragment, whereSQL)
		}
	}
	if len(args) != 8 {
		t.Fatalf("args length = %d, want 8: %#v", len(args), args)
	}
	for _, index := range []int{2, 3, 4, 5, 7} {
		if args[index] != "%10086%" {
			t.Fatalf("target keyword arg[%d] = %#v, want %%10086%%", index, args[index])
		}
	}
	if _, ok := args[6].(int64); !ok {
		t.Fatalf("pretty lease expiry arg type = %T, want int64: %+v", args[6], args)
	}
}

func TestBanListWhereSQLBuildsOperatorKeywordFilter(t *testing.T) {
	whereSQL, args := banListWhereSQL(context.Background(), banListQuery{
		OperatorKeyword: "admin",
		StartMs:         1000,
		EndMs:           2000,
	}, []int64{7, 9})

	for _, fragment := range []string{
		"l.operator_type = 'app_user'",
		"operator_user.current_display_user_id LIKE ?",
		"operator_user.default_display_user_id LIKE ?",
		"pretty_display_user_id_leases lease",
		"(l.operator_type = 'admin' AND l.operator_user_id IN (?,?))",
		"l.created_at_ms >= ?",
		"l.created_at_ms < ?",
	} {
		if !strings.Contains(whereSQL, fragment) {
			t.Fatalf("where sql missing %q: %s", fragment, whereSQL)
		}
	}
	wantArgs := []any{"lalu", "lalu", "%admin%", "%admin%", "%admin%", "%admin%", int64(0), "%admin%", int64(7), int64(9), int64(1000), int64(2000)}
	if len(args) != len(wantArgs) {
		t.Fatalf("args length = %d, want %d: %#v", len(args), len(wantArgs), args)
	}
	for index := range wantArgs {
		if index == 6 {
			if _, ok := args[index].(int64); !ok {
				t.Fatalf("arg[%d] type = %T, want int64: %#v", index, args[index], args)
			}
			continue
		}
		if args[index] != wantArgs[index] {
			t.Fatalf("arg[%d] = %#v, want %#v", index, args[index], wantArgs[index])
		}
	}
}
