package bunmodel

import (
	"fmt"

	"gitea.dwysokinski.me/twhelp/corev3/internal/domain"
	"github.com/uptrace/bun"
)

type Version struct {
	bun.BaseModel `bun:"table:versions,alias:version"`

	Code     string `bun:"code,pk"`
	Name     string `bun:"name"`
	Host     string `bun:"host"`
	Timezone string `bun:"timezone"`
}

func (v Version) ToDomain() (domain.Version, error) {
	return domain.UnmarshalVersionFromDatabase(
		v.Code,
		v.Name,
		v.Host,
		v.Timezone,
	)
}

type Versions []Version

func (vs Versions) ToDomain() (domain.Versions, error) {
	res := make(domain.Versions, 0, len(vs))

	for _, v := range vs {
		converted, err := v.ToDomain()
		if err != nil {
			return nil, fmt.Errorf("couldn't construct domain.Version (version=%s): %w", v.Code, err)
		}

		res = append(res, converted)
	}

	return res, nil
}
