package twitch

import (
	"slices"

	"github.com/nicklaw5/helix/v2"

	"git.sr.ht/~ashkeel/strimertul/database"
)

var scopes = []string{
	"bits:read",
	"channel:bot",
	"channel:moderate",
	"channel:read:hype_train",
	"channel:read:polls",
	"channel:read:predictions",
	"channel:read:redemptions",
	"channel:read:subscriptions",
	"chat:edit",
	"chat:read",
	"moderator:manage:announcements",
	"moderator:read:chatters",
	"moderator:read:followers",
	"user:bot",
	"user:manage:whispers",
	"user:read:chat",
	"user:write:chat",
	"user_read",
	"whispers:edit",
	"whispers:read",
}

// CheckScopes checks if the user has authorized all required scopes
// Normally this would be the case but between versions strimertul has changed
// the required scopes, and it's possible that some users have not re-authorized
// the application with the new scopes.
func CheckScopes(db database.Database) (bool, error) {
	var authResp AuthResponse
	if err := db.GetJSON(AuthKey, &authResp); err != nil {
		return false, err
	}

	// Sort scopes for comparison
	slices.Sort(authResp.Scope)
	slices.Sort(scopes)

	return slices.Equal(scopes, authResp.Scope), nil
}

func GetAuthorizationURL(api *helix.Client, state string) string {
	if api == nil {
		return "twitch-not-configured"
	}
	return api.GetAuthorizationURL(&helix.AuthorizationURLParams{
		ResponseType: "code",
		Scopes:       scopes,
		State:        state,
		ForceVerify:  true,
	})
}
