package internal

import (
	"errors"
	"fmt"
	"net/http"
	"os"
	"path"

	"code.justin.tv/video/amzncorp"
)

// NewMidwayClient returns a http.Client that uses the midway cookie from the ~/.midway/cookie
func NewMidwayClient() (*http.Client, error) {
	homedir, err := os.UserHomeDir()
	if err != nil {
		return nil, fmt.Errorf("expected a home directory to be configured on the system: %w", err)
	}

	f, err := os.Open(path.Join(homedir, ".midway/cookie"))
	if err != nil {
		return nil, errors.New("could not read midway cookie: please run: mwinit --aea")
	}

	client, err := amzncorp.MidwayClient(f)
	if err != nil {
		return nil, fmt.Errorf("error creating midway client: %w", err)
	}

	return client, nil
}
