package spotify

import (
	"fmt"
	"net/url"
	"strings"
)

func ParsePlaylistID(input string) (string, error) {
	s := strings.TrimSpace(input)
	if s == "" {
		return "", fmt.Errorf("empty playlist input")
	}

	if strings.HasPrefix(s, "spotify:playlist:") {
		id := strings.TrimSpace(strings.TrimPrefix(s, "spotify:playlist:"))
		if id == "" {
			return "", fmt.Errorf("invalid spotify URI")
		}
		return id, nil
	}

	if !strings.Contains(s, "://") {
		return s, nil
	}

	u, err := url.Parse(s)
	if err != nil {
		return "", fmt.Errorf("invalid playlist URL")
	}
	parts := strings.Split(strings.Trim(u.Path, "/"), "/")
	for i := 0; i < len(parts)-1; i++ {
		if parts[i] == "playlist" {
			id := strings.TrimSpace(parts[i+1])
			if id == "" {
				return "", fmt.Errorf("missing playlist id in URL")
			}
			return id, nil
		}
	}

	return "", fmt.Errorf("could not find playlist id in URL")
}
