package roomadmin

import (
	"errors"
	"testing"
)

func TestNormalizeRoomPinListQueryDefaultsToActive(t *testing.T) {
	query := normalizeRoomPinListQuery(roomPinListQuery{Page: -1, PageSize: 200, Status: "unknown", RegionID: -10, Keyword: " 123 "})
	if query.Page != 1 || query.PageSize != 100 {
		t.Fatalf("pagination normalization mismatch: %+v", query)
	}
	if query.Status != roomPinStatusActive || query.RegionID != 0 || query.Keyword != "123" {
		t.Fatalf("filter normalization mismatch: %+v", query)
	}
}

func TestNormalizeCreateRoomPinRequestDefaultsDuration(t *testing.T) {
	req, err := normalizeCreateRoomPinRequest(createRoomPinRequest{RoomID: " room-1 ", Weight: 10})
	if err != nil {
		t.Fatalf("normalize create pin failed: %v", err)
	}
	if req.RoomID != "room-1" || req.DurationDays != defaultRoomPinDays || req.PinType != roomPinTypeRegion || req.Weight != 10 {
		t.Fatalf("create pin normalization mismatch: %+v", req)
	}
	if req.PinnedAtMS <= 0 || req.ExpiresAtMS <= req.PinnedAtMS {
		t.Fatalf("create pin interval should be normalized: %+v", req)
	}
}

func TestNormalizeCreateRoomPinRequestAcceptsExplicitIntervalAndType(t *testing.T) {
	req, err := normalizeCreateRoomPinRequest(createRoomPinRequest{
		RoomID:      "room-1",
		PinType:     roomPinTypeGlobal,
		Weight:      10,
		PinnedAtMS:  1000,
		ExpiresAtMS: 2000,
	})
	if err != nil {
		t.Fatalf("normalize explicit create pin failed: %v", err)
	}
	if req.PinType != roomPinTypeGlobal || req.DurationDays != 1 || req.PinnedAtMS != 1000 || req.ExpiresAtMS != 2000 {
		t.Fatalf("explicit interval normalization mismatch: %+v", req)
	}
}

func TestNormalizeCreateRoomPinRequestRejectsInvalidInput(t *testing.T) {
	tests := []struct {
		name string
		req  createRoomPinRequest
	}{
		{name: "empty_room", req: createRoomPinRequest{Weight: 1, DurationDays: 30}},
		{name: "negative_weight", req: createRoomPinRequest{RoomID: "room-1", Weight: -1, DurationDays: 30}},
		{name: "duration_too_large", req: createRoomPinRequest{RoomID: "room-1", Weight: 1, DurationDays: maxRoomPinDays + 1}},
		{name: "bad_interval", req: createRoomPinRequest{RoomID: "room-1", Weight: 1, PinnedAtMS: 2000, ExpiresAtMS: 1000}},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			_, err := normalizeCreateRoomPinRequest(test.req)
			if !errors.Is(err, ErrInvalidArgument) {
				t.Fatalf("expected ErrInvalidArgument, got %v", err)
			}
		})
	}
}
