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"
)

// Unhost a channel.
func (l *Impl) Unhost(ctx context.Context, userID, channelID string) error {
	allow := l.rateLimiter.RateLimitUnhostBySourceID(ctx, channelID)
	if !allow {
		return autohosterrors.TooManyRequests(
			fmt.Sprintf("unhost operation rate-limited. source_id=\"%s\"", channelID))
	}

	err := l.unhostImpl(ctx, userID, channelID)

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

	return err
}

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

	return l.hostmode.Unhost(ctx, channelID)
}
