package configloader

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

// Validates a museum-digital instance URL to upload to.
// The link must be a valid URL. As it can be expected that people will
// enter broken values, the URL should be reduced to its hostname and
// rebuilt from there.
func ValidateInstanceLink(instanceUrl string) (string, error) {

    parsed, err := url.Parse(instanceUrl)
    if err != nil {
        return "", err
    }

    // Check the hostname contains "museum-digital.de" or "museum-digital.org"
    if !strings.HasSuffix(parsed.Host, "museum-digital.de") && !strings.HasSuffix(parsed.Host, "museum-digital.org") {
        return "", errors.New("This tool only supports uploading to XYZ.museum-digital.de or XYZ.museum-digital.org")
    }

    // Check /musdb is available on the md instance
    musdbUrl := url.URL{
        Scheme: "https",
        Host: parsed.Host,
        Path: "/musdb",
    }
    statusCode, err := HttpGetStatusCode(musdbUrl.String())
	if err != nil {
		return "", err
	}
	if statusCode > 399 {
        return "", errors.New("The museum-digital subdomain does not contain a musdb path")
	}

    // https should be assumed and enforced.
    url := url.URL{
        Scheme: "https",
        Host: parsed.Host,
    }
    return url.String(), nil

}
