package domain

import (
	"net/url"
)

type SyncServersCmdPayload struct {
	versionCode string
	url         *url.URL
}

const syncServersCmdPayloadModelName = "SyncServersCmdPayload"

func NewSyncServersCmdPayload(versionCode string, u *url.URL) (SyncServersCmdPayload, error) {
	if versionCode == "" {
		return SyncServersCmdPayload{}, ValidationError{
			Model: syncServersCmdPayloadModelName,
			Field: "versionCode",
			Err:   ErrRequired,
		}
	}

	if u == nil {
		return SyncServersCmdPayload{}, ValidationError{
			Model: syncServersCmdPayloadModelName,
			Field: "url",
			Err:   ErrNil,
		}
	}

	return SyncServersCmdPayload{versionCode: versionCode, url: u}, nil
}

func (p SyncServersCmdPayload) VersionCode() string {
	return p.versionCode
}

func (p SyncServersCmdPayload) URL() *url.URL {
	return p.url
}

type ServerSyncedEventPayload struct {
	key         string
	url         *url.URL
	versionCode string
}

const serverSyncedEventPayloadModelName = "ServerSyncedEventPayload"

func NewServerSyncedEventPayload(key string, u *url.URL, versionCode string) (ServerSyncedEventPayload, error) {
	if key == "" {
		return ServerSyncedEventPayload{}, ValidationError{
			Model: serverSyncedEventPayloadModelName,
			Field: "key",
			Err:   ErrRequired,
		}
	}

	if versionCode == "" {
		return ServerSyncedEventPayload{}, ValidationError{
			Model: serverSyncedEventPayloadModelName,
			Field: "versionCode",
			Err:   ErrRequired,
		}
	}

	if u == nil {
		return ServerSyncedEventPayload{}, ValidationError{
			Model: serverSyncedEventPayloadModelName,
			Field: "url",
			Err:   ErrNil,
		}
	}

	return ServerSyncedEventPayload{
		key:         key,
		url:         u,
		versionCode: versionCode,
	}, nil
}

func NewServerSyncedEventPayloads(servers BaseServers, versionCode string) ([]ServerSyncedEventPayload, error) {
	res := make([]ServerSyncedEventPayload, 0, len(servers))

	for _, s := range servers {
		payload, err := NewServerSyncedEventPayload(s.Key(), s.URL(), versionCode)
		if err != nil {
			return nil, err
		}

		res = append(res, payload)
	}

	return res, nil
}

func (p ServerSyncedEventPayload) Key() string {
	return p.key
}

func (p ServerSyncedEventPayload) URL() *url.URL {
	return p.url
}

func (p ServerSyncedEventPayload) VersionCode() string {
	return p.versionCode
}
