package domain

import (
	"net/url"
)

const (
	versionCodeMinLength = 2
	versionCodeMaxLength = 2
)

type Version struct {
	code     string
	name     string
	host     string
	timezone string
}

var versionModelName = "Version"

// UnmarshalVersionFromDatabase unmarshals Version from the database.
//
// It should be used only for unmarshalling from the database!
// You can't use UnmarshalVersionFromDatabase as constructor - It may put domain into the invalid state!
func UnmarshalVersionFromDatabase(
	code string,
	name string,
	host string,
	timezone string,
) (Version, error) {
	if code == "" {
		return Version{}, ValidationError{
			Model: versionModelName,
			Field: "code",
			Err:   ErrRequired,
		}
	}

	if name == "" {
		return Version{}, ValidationError{
			Model: versionModelName,
			Field: "name",
			Err:   ErrRequired,
		}
	}

	if host == "" {
		return Version{}, ValidationError{
			Model: versionModelName,
			Field: "host",
			Err:   ErrRequired,
		}
	}

	if timezone == "" {
		return Version{}, ValidationError{
			Model: versionModelName,
			Field: "timezone",
			Err:   ErrRequired,
		}
	}

	return Version{
		code:     code,
		name:     name,
		host:     host,
		timezone: timezone,
	}, nil
}

func (v Version) Code() string {
	return v.code
}

func (v Version) Name() string {
	return v.name
}

func (v Version) Host() string {
	return v.host
}

func (v Version) Timezone() string {
	return v.timezone
}

func (v Version) URL() *url.URL {
	return &url.URL{
		Scheme: "https",
		Host:   v.host,
	}
}

type Versions []Version

type VersionSort uint8

const (
	VersionSortCodeASC VersionSort = iota + 1
	VersionSortCodeDESC
)

type ListVersionsParams struct {
	sort []VersionSort
}

const listVersionsParamsModelName = "ListVersionsParams"

func NewListVersionsParams() ListVersionsParams {
	return ListVersionsParams{sort: []VersionSort{VersionSortCodeASC}}
}

const (
	versionSortMinLength = 1
	versionSortMaxLength = 1
)

func (params *ListVersionsParams) Sort() []VersionSort {
	return params.sort
}

func (params *ListVersionsParams) SetSort(sort []VersionSort) error {
	if err := validateSliceLen(sort, versionSortMinLength, versionSortMaxLength); err != nil {
		return ValidationError{
			Model: listVersionsParamsModelName,
			Field: "sort",
			Err:   err,
		}
	}

	params.sort = sort

	return nil
}
