package util

import (
	"fmt"
	"testing"
)

func FindSubscriptionByChanName(t *testing.T, baseUrl string, subscriber Userdat, ownerUID string, chanName string) (subscriptionID string, channelID string) {
	type subobj struct {
		SubscriptionId      string `json:"subscription_id"`
		ChannelId           string `json:"channel_id"`
		ChannelInternalName string `json:"channel_internal_name"`
		ChannelOwnerUserId  string `json:"channel_owner_user_id"`
		Confirmed           bool   `json:"confirmed"`
		Active              bool   `json:"active"`
	}
	type sublist struct {
		Subscriptions []subobj `json:"subscriptions"`
	}

	subs := RequestAuthGet[sublist](t, subscriber.AdminKey, baseUrl, fmt.Sprintf("/api/v2/users/%s/subscriptions?direction=outgoing", subscriber.UID))

	for _, sub := range subs.Subscriptions {
		if sub.ChannelOwnerUserId == ownerUID && sub.ChannelInternalName == chanName {
			fullSub := RequestAuthGet[subobj](t, subscriber.AdminKey, baseUrl, fmt.Sprintf("/api/v2/users/%s/subscriptions/%s", subscriber.UID, sub.SubscriptionId))
			if fullSub.ChannelOwnerUserId == ownerUID && fullSub.ChannelInternalName == chanName {
				return fullSub.SubscriptionId, fullSub.ChannelId
			}
		}
	}

	t.Fatalf("Could not find subscription for user %s to channel %s owned by %s", subscriber.UID, chanName, ownerUID)
	return "", ""
}