package userapi

import (
	"encoding/json"
	"net/http"
	"strconv"
	"strings"

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

type submitReportData struct {
	ReportID    string `json:"report_id"`
	TargetType  string `json:"target_type"`
	UserID      string `json:"user_id"`
	RoomID      string `json:"room_id"`
	ReportType  string `json:"report_type"`
	Status      string `json:"status"`
	CreatedAtMs int64  `json:"created_at_ms"`
}

// submitReport 只把当前登录用户和举报目标透传到 user-service；举报发起人不能来自客户端 body。
func (h *Handler) submitReport(writer http.ResponseWriter, request *http.Request) {
	if h.userSocialClient == nil {
		httpkit.WriteError(writer, request, http.StatusBadGateway, httpkit.CodeUpstreamError, "upstream service error")
		return
	}
	var body struct {
		UserID     json.RawMessage `json:"user_id"`
		RoomID     string          `json:"room_id"`
		ReportType string          `json:"report_type"`
		Reason     string          `json:"reason"`
		ImageURLs  []string        `json:"image_urls"`
	}
	if !httpkit.Decode(writer, request, &body) {
		return
	}
	userID, ok := optionalReportUserID(body.UserID)
	if !ok {
		httpkit.WriteError(writer, request, http.StatusBadRequest, httpkit.CodeInvalidArgument, "invalid argument")
		return
	}
	resp, err := h.userSocialClient.SubmitReport(request.Context(), &userv1.SubmitReportRequest{
		Meta:           httpkit.UserMeta(request, ""),
		ReporterUserId: auth.UserIDFromContext(request.Context()),
		UserId:         userID,
		RoomId:         body.RoomID,
		ReportType:     body.ReportType,
		Reason:         body.Reason,
		ImageUrls:      body.ImageURLs,
	})
	if err != nil {
		httpkit.WriteRPCError(writer, request, err)
		return
	}
	httpkit.WriteOK(writer, request, reportData(resp.GetReport()))
}

func optionalReportUserID(raw json.RawMessage) (int64, bool) {
	if len(raw) == 0 || string(raw) == "null" {
		return 0, true
	}
	var text string
	if err := json.Unmarshal(raw, &text); err == nil {
		text = strings.TrimSpace(text)
		if text == "" {
			return 0, true
		}
		value, err := strconv.ParseInt(text, 10, 64)
		return value, err == nil && value > 0
	}
	var value int64
	if err := json.Unmarshal(raw, &value); err != nil {
		return 0, false
	}
	return value, value > 0
}

func reportData(report *userv1.UserReport) submitReportData {
	if report == nil {
		return submitReportData{}
	}
	return submitReportData{
		ReportID:    report.GetReportId(),
		TargetType:  report.GetTargetType(),
		UserID:      httpkit.UserIDString(report.GetUserId()),
		RoomID:      report.GetRoomId(),
		ReportType:  report.GetReportType(),
		Status:      report.GetStatus(),
		CreatedAtMs: report.GetCreatedAtMs(),
	}
}
