package extsvc

import (
	"fmt"
	"strings"
)

// Configured reports what a service still needs before it can be uploaded to.
//
// It exists so the answer lives NEXT TO THE UPLOADERS that enforce it. Written
// once in the app instead, it drifted immediately: Club Log was refused for a
// missing API key, which nobody has ever set — OpsLog carries its own
// application key (see clublogAppAPIKey) and the account is an email, a password
// and the logbook callsign. An operator whose live upload had been working for
// months was told his service was not configured.
//
// Each case mirrors the guard at the top of the matching Upload* function. It
// answers "can this be attempted", not "are these credentials right": only the
// service can say that, and it says it by refusing the upload.
func Configured(svc Service, cfg ExternalServices) error {
	missing := func(service string, fields ...string) error {
		return fmt.Errorf("%s is not configured — %s", service, strings.Join(fields, ", "))
	}
	set := func(v string) bool { return strings.TrimSpace(v) != "" }
	var need []string
	add := func(ok bool, what string) {
		if !ok {
			need = append(need, what)
		}
	}

	switch svc {
	case ServiceQRZ:
		add(set(cfg.QRZ.APIKey), "the logbook API key")
		if len(need) > 0 {
			return missing("QRZ.com", need...)
		}
	case ServiceClublog:
		// No API key: OpsLog's own application key is embedded.
		add(set(cfg.Clublog.Email), "the account email")
		add(set(cfg.Clublog.Password), "the password")
		add(set(cfg.Clublog.Callsign), "the logbook callsign")
		if len(need) > 0 {
			return missing("Club Log", need...)
		}
	case ServiceHRDLog:
		add(set(cfg.HRDLog.Callsign), "the station callsign")
		add(set(cfg.HRDLog.Code), "the upload code")
		if len(need) > 0 {
			return missing("HRDLog.net", need...)
		}
	case ServiceEQSL:
		add(set(cfg.EQSL.Username), "the username (callsign)")
		add(set(cfg.EQSL.Password), "the password")
		if len(need) > 0 {
			return missing("eQSL.cc", need...)
		}
	case ServiceHamQTH:
		add(set(cfg.HamQTH.Username), "the username")
		add(set(cfg.HamQTH.Password), "the password")
		if len(need) > 0 {
			return missing("HamQTH", need...)
		}
	case ServiceCloudlog:
		add(set(cfg.Cloudlog.URL), "the instance URL")
		add(set(cfg.Cloudlog.APIKey), "the API key")
		add(set(cfg.Cloudlog.StationID), "the station profile")
		if len(need) > 0 {
			return missing("Cloudlog / Wavelog", need...)
		}
	case ServiceLoTW:
		add(set(cfg.LoTW.TQSLPath), "the path to tqsl.exe")
		add(set(cfg.LoTW.StationLocation), "the TQSL station location")
		if len(need) > 0 {
			return missing("LoTW", need...)
		}
	}
	return nil
}
