package activityapi

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	luckygiftv1 "hyapp.local/api/proto/luckygift/v1"
	"hyapp/pkg/appcode"
	"hyapp/services/gateway-service/internal/auth"
)

func TestCheckLuckyGiftForwardsEligibilityRequest(t *testing.T) {
	client := &fakeLuckyGiftClient{resp: &luckygiftv1.CheckLuckyGiftResponse{
		Enabled:        true,
		Reason:         "enabled",
		GiftId:         "rose",
		PoolId:         "super_lucky",
		GiftPrice:      100,
		RuleVersion:    3,
		TargetRtpPpm:   600000,
		ExperiencePool: "novice",
	}}
	handler := New(Config{LuckyGift: client})
	request := httptest.NewRequest(http.MethodPost, "/api/v1/activities/lucky-gifts/check", strings.NewReader(`{"room_id":"room-1","gift_id":"rose","pool_id":"super_lucky"}`))
	request = request.WithContext(auth.WithUserID(appcode.WithContext(request.Context(), "lalu"), 42))
	recorder := httptest.NewRecorder()

	handler.checkLuckyGift(recorder, request)

	if recorder.Code != http.StatusOK {
		t.Fatalf("status mismatch: %d body=%s", recorder.Code, recorder.Body.String())
	}
	if client.last == nil || client.last.GetUserId() != 42 || client.last.GetRoomId() != "room-1" || client.last.GetGiftId() != "rose" || client.last.GetPoolId() != "super_lucky" {
		t.Fatalf("check request mismatch: %+v", client.last)
	}
	var envelope struct {
		Code string `json:"code"`
		Data struct {
			Enabled        bool   `json:"enabled"`
			Reason         string `json:"reason"`
			ExperiencePool string `json:"experience_pool"`
		} `json:"data"`
	}
	if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if envelope.Code != "OK" || !envelope.Data.Enabled || envelope.Data.ExperiencePool != "novice" {
		t.Fatalf("response mismatch: %+v", envelope)
	}
}

type fakeLuckyGiftClient struct {
	last *luckygiftv1.CheckLuckyGiftRequest
	resp *luckygiftv1.CheckLuckyGiftResponse
}

func (c *fakeLuckyGiftClient) CheckLuckyGift(_ context.Context, req *luckygiftv1.CheckLuckyGiftRequest) (*luckygiftv1.CheckLuckyGiftResponse, error) {
	c.last = req
	return c.resp, nil
}
