package gameapi

import (
	"net/http"
	"strings"
	"time"

	userv1 "hyapp.local/api/proto/user/v1"
	"hyapp/pkg/appcode"
	"hyapp/services/gateway-service/internal/auth"
	"hyapp/services/gateway-service/internal/client"
	"hyapp/services/gateway-service/internal/transport/http/httpkit"
)

type selfGameH5EventRequest struct {
	EventID       string `json:"event_id"`
	EventName     string `json:"event_name"`
	GameID        string `json:"game_id"`
	Page          string `json:"page"`
	SessionID     string `json:"session_id"`
	MatchID       string `json:"match_id"`
	Language      string `json:"language"`
	ClientVersion string `json:"client_version"`
	H5Version     string `json:"h5_version"`
	EntrySource   string `json:"entry_source"`
	DurationMS    int64  `json:"duration_ms"`
	Success       bool   `json:"success"`
	ErrorCode     string `json:"error_code"`
	OccurredAtMS  int64  `json:"occurred_at_ms"`
}

func (h *Handler) reportSelfGameH5Event(writer http.ResponseWriter, request *http.Request) {
	if h.statisticsClient == nil || h.userProfileClient == nil {
		httpkit.WriteError(writer, request, http.StatusBadGateway, httpkit.CodeUpstreamError, "upstream service error")
		return
	}
	var body selfGameH5EventRequest
	if err := httpkit.DecodeJSON(request.Body, &body); err != nil {
		httpkit.WriteError(writer, request, http.StatusBadRequest, httpkit.CodeInvalidJSON, "invalid request body")
		return
	}
	body.EventID = strings.TrimSpace(body.EventID)
	body.EventName = strings.TrimSpace(body.EventName)
	body.GameID = strings.TrimSpace(body.GameID)
	if body.EventID == "" || body.EventName == "" || body.GameID == "" {
		httpkit.WriteError(writer, request, http.StatusBadRequest, httpkit.CodeInvalidArgument, "invalid argument")
		return
	}
	userID := auth.UserIDFromContext(request.Context())
	userResp, err := h.userProfileClient.GetUser(request.Context(), &userv1.GetUserRequest{
		Meta:   httpkit.UserMeta(request, ""),
		UserId: userID,
	})
	if err != nil {
		httpkit.WriteRPCError(writer, request, err)
		return
	}
	if body.OccurredAtMS <= 0 {
		body.OccurredAtMS = time.Now().UTC().UnixMilli()
	}
	language := strings.TrimSpace(body.Language)
	if language == "" {
		language = requestLanguage(request)
	}
	clientVersion := strings.TrimSpace(body.ClientVersion)
	if clientVersion == "" {
		clientVersion = httpkit.FirstHeader(request, "X-App-Version", "X-Client-Version")
	}
	// H5 上报只信任客户端的行为事实和耗时；用户、App、国家和区域由 gateway 根据登录态补齐，避免前端伪造维度污染统计口径。
	err = h.statisticsClient.ReportSelfGameH5Event(request.Context(), client.SelfGameH5Event{
		AppCode:       appcode.FromContext(request.Context()),
		EventID:       body.EventID,
		EventName:     body.EventName,
		GameID:        body.GameID,
		Page:          body.Page,
		SessionID:     body.SessionID,
		MatchID:       body.MatchID,
		UserID:        userID,
		CountryID:     userResp.GetUser().GetCountryId(),
		RegionID:      userResp.GetUser().GetRegionId(),
		Language:      language,
		ClientVersion: clientVersion,
		H5Version:     body.H5Version,
		EntrySource:   body.EntrySource,
		DurationMS:    body.DurationMS,
		Success:       body.Success,
		ErrorCode:     body.ErrorCode,
		OccurredAtMS:  body.OccurredAtMS,
	})
	if err != nil {
		httpkit.WriteError(writer, request, http.StatusBadGateway, httpkit.CodeUpstreamError, "upstream service error")
		return
	}
	httpkit.WriteOK(writer, request, map[string]any{"ok": true})
}
