package bunmodel

import (
	"fmt"
	"time"

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

type Village struct {
	bun.BaseModel `bun:"table:villages,alias:village"`

	ID         int       `bun:"id,nullzero,pk"`
	ServerKey  string    `bun:"server_key,nullzero,pk"`
	Name       string    `bun:"name,nullzero"`
	Points     int       `bun:"points"`
	X          int       `bun:"x"`
	Y          int       `bun:"y"`
	Continent  string    `bun:"continent"`
	Bonus      int       `bun:"bonus"`
	PlayerID   int       `bun:"player_id,nullzero"`
	Player     Player    `bun:"player,rel:belongs-to,join:player_id=id,join:server_key=server_key"`
	ProfileURL string    `bun:"profile_url,nullzero"`
	CreatedAt  time.Time `bun:"created_at,nullzero"`
}

func (v Village) ToDomain() (domain.Village, error) {
	converted, err := domain.UnmarshalVillageFromDatabase(
		v.ID,
		v.ServerKey,
		v.Name,
		v.Points,
		v.X,
		v.Y,
		v.Continent,
		v.Bonus,
		v.PlayerID,
		v.ProfileURL,
		v.CreatedAt,
	)
	if err != nil {
		return domain.Village{}, fmt.Errorf(
			"couldn't construct domain.Village (id=%d,serverKey=%s): %w",
			v.ID,
			v.ServerKey,
			err,
		)
	}

	return converted, nil
}

type Villages []Village

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

	for _, v := range vs {
		converted, err := v.ToDomain()
		if err != nil {
			return nil, err
		}

		res = append(res, converted)
	}

	return res, nil
}
