package main

import (
	"fmt"
	"net/http"
	"encoding/json"
)

type SpotifyResponse struct {
       ID string
       Name string
       Popularity int
       Genres []string
}

// Makes a request to spotify API to grab artist data
// And parse the results into a properly typed struct
func getSpotifyArtistData(artistID string, spotifyAuthToken string) (SpotifyResponse, error) {

	artistEndpoint := fmt.Sprintf("https://api.spotify.com/v1/artists/%s", artistID)
    req, err := http.NewRequest("GET", artistEndpoint, nil)
    if err != nil {
		return SpotifyResponse{}, fmt.Errorf("Failed to build HTTP request to spotify: %w", err)
    }
    req.Header.Add("Authorization", spotifyAuthToken)

    // Send off request
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
		return SpotifyResponse{}, fmt.Errorf("Failed to get artist data from spotify API: %w", err)
	} else if resp.StatusCode != 200 {
		return SpotifyResponse{}, fmt.Errorf("Failed to get artist data from spotify API due to response status: %s", resp.Status)
    }
	
	var spotifyResponse SpotifyResponse
	err = json.NewDecoder(resp.Body).Decode(&spotifyResponse)
    if err != nil {
        return SpotifyResponse{}, fmt.Errorf("Failed to read response body data from spotify: %w", err)
    }
    
    // Close this immediately since it's unused now
    resp.Body.Close()

	// After all the above checks we assume this response is populated
	// If errors arise we can do extra validation here
	return spotifyResponse, nil
}