// Package characters holds functions that interact with the characters
package characters

import (
	"fmt"

	"git.stinnesbeck.com/nils/artifacts/api"
)

// GetMy retrieves all characters from your account
func GetMy() ([]Character, error) {
	// these are the possible response codes, other than 200 OK
	responseCodes := map[int]string{
		404: "Characters not found",
	}

	// use Get function to retrieve characters
	return api.Get[[]Character]("/my/characters/", responseCodes)
}

// GetAll tries to retrieve all characters on the server
func GetAll() ([]Character, error) {
	// these are the possible response codes, other than 200 OK
	responseCodes := map[int]string{
		404: "Characters not found",
	}

	// use Get function to retrieve characters
	return api.Get[[]Character]("/characters/", responseCodes)
}

// Get tries to retrieve a character by name
func Get(name string) (Character, error) {
	// these are the possible response codes, other than 200 OK
	responseCodes := map[int]string{
		404: "Character not found",
	}

	// use Get function to retrieve character
	return api.Get[Character](fmt.Sprintf("/characters/%s", name), responseCodes)
}

// Create will try to create a new character
func Create(name string, skin Skin) (Character, error) {
	if len(name) > 12 {
		return Character{}, fmt.Errorf("make sure to provide a name that is >=3 and <=12 characters long")
	}

	// these are the possible response codes, other than 200 OK
	responseCodes := map[int]string{
		494: "Name already used",
		495: "Maximum characters reached on your account",
	}

	newChar := Character{
		Name: name,
		Skin: skin,
	}

	return api.Post[Character]("/characters/create", newChar, responseCodes)
}

func (c *Character) Refresh() error {
	char, err := Get(c.Name)
	if err != nil {
		return err
	}

	*c = char

	return nil
}