package logic

import (
	"context"
	"fmt"

	"code.justin.tv/creator-collab/log"
	"code.justin.tv/live/autohost/internal/logfield"

	autohosterrors "code.justin.tv/live/autohost/internal/errors"
)

// HostTarget starts hosting the target channel on the source channel
func (l *Impl) HostTarget(ctx context.Context, userID, channelID, targetID string) error {
	allow := l.rateLimiter.RateLimitHostBySourceID(ctx, channelID)
	if !allow {
		return autohosterrors.TooManyRequests(
			fmt.Sprintf("host operation rate-limited. source_id=\"%s\"", channelID))
	}

	err := l.hostTargetImpl(ctx, userID, channelID, targetID)

	l.accessLogger.Log("HostTarget", err, log.Fields{
		logfield.HosterChannelID:     channelID,
		logfield.HostTargetChannelID: targetID,
		logfield.HostCallerChannelID: userID,
	})

	return err
}

func (l *Impl) hostTargetImpl(ctx context.Context, userID, channelID, targetID string) error {
	authorized, err := l.auth.CanUseHosting(ctx, userID, channelID)
	if err != nil {
		return err
	}
	if !authorized {
		return autohosterrors.Forbidden
	}

	isAutohost := false
	isPostRaidHost := false
	return l.hostmode.Host(ctx, channelID, targetID, isAutohost, isPostRaidHost)
}
