package methods

import (
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"sevenkeys/scryfall/types"
)

const SETS_API_URL string = "https://api.scryfall.com/sets"

func GetSets() ([]types.Set, error) {
	response, err := http.Get(SETS_API_URL)
	if err != nil {
		return []types.Set{}, nil
	}

	if response.StatusCode != http.StatusOK {
		return []types.Set{}, errors.New("HTTP request failed with code: " + string(response.StatusCode))
	}

	defer response.Body.Close()
	setsBytes, err := io.ReadAll(response.Body)
	if err != nil {
		return []types.Set{}, err
	}

	var setList types.SetList
	err = json.Unmarshal(setsBytes, &setList)
	if err != nil {
		return []types.Set{}, err
	}

	return setList.Data, nil
}
