package service

import (
	"context"
	"strings"

	roomv1 "hyapp.local/api/proto/room/v1"
	"hyapp/pkg/xerr"
	"hyapp/services/room-service/internal/room/state"
)

type RobotSendGiftInput struct {
	Meta                   *roomv1.RequestMeta
	TargetUserID           int64
	GiftID                 string
	GiftCount              int32
	PoolID                 string
	RobotUserIDs           []int64
	SyntheticRewardCoins   int64
	SyntheticMultiplierPPM int64
	RealRoomHeat           bool
}

type robotGiftOptions struct {
	Enabled                bool
	RobotUserIDs           []int64
	SyntheticRewardCoins   int64
	SyntheticMultiplierPPM int64
	RealRoomHeat           bool
}

func (s *Service) RobotSendGift(ctx context.Context, input RobotSendGiftInput) (*roomv1.SendGiftResponse, error) {
	req := &roomv1.SendGiftRequest{
		Meta:          input.Meta,
		TargetUserId:  input.TargetUserID,
		TargetUserIds: []int64{input.TargetUserID},
		GiftId:        input.GiftID,
		GiftCount:     input.GiftCount,
		TargetType:    "user",
		PoolId:        input.PoolID,
	}
	return s.sendGift(ctx, req, giftSendOptions{
		Robot: robotGiftOptions{
			Enabled:                true,
			RobotUserIDs:           input.RobotUserIDs,
			SyntheticRewardCoins:   input.SyntheticRewardCoins,
			SyntheticMultiplierPPM: input.SyntheticMultiplierPPM,
			RealRoomHeat:           input.RealRoomHeat,
		},
	})
}

func requireRobotGiftParticipants(current *state.RoomState, senderUserID int64, targetUserIDs []int64, runtimeRobotUserIDs []int64, requireRobotRoom bool) error {
	if current == nil {
		return xerr.New(xerr.PermissionDenied, "robot gift requires room state")
	}
	if requireRobotRoom && (current == nil || current.RoomExt[roomExtRobotRoomKey] != "true") {
		return xerr.New(xerr.PermissionDenied, "robot gift requires robot room")
	}
	allowed := parseInt64CSV(current.RoomExt[roomExtRobotUserIDsKey])
	for _, userID := range runtimeRobotUserIDs {
		if userID > 0 {
			allowed[userID] = true
		}
	}
	if !allowed[senderUserID] {
		return xerr.New(xerr.PermissionDenied, "robot sender is not allowed")
	}
	for _, targetUserID := range targetUserIDs {
		if !allowed[targetUserID] {
			return xerr.New(xerr.PermissionDenied, "robot gift target is not allowed")
		}
	}
	return nil
}

func normalizeGiftTargetType(raw string) string {
	raw = strings.TrimSpace(raw)
	switch raw {
	case "", "user", "all_mic", "all_room", "couple":
		return raw
	default:
		return raw
	}
}
