package bunmodel

import (
	"fmt"
	"time"

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

type TribeSnapshot struct {
	bun.BaseModel `bun:"table:tribe_snapshots,alias:ts"`

	ID          int       `bun:"id,pk,autoincrement,identity"`
	TribeID     int       `bun:"tribe_id,nullzero"`
	ServerKey   string    `bun:"server_key,nullzero"`
	NumMembers  int       `bun:"num_members"`
	NumVillages int       `bun:"num_villages"`
	Points      int       `bun:"points"`
	AllPoints   int       `bun:"all_points"`
	Rank        int       `bun:"rank"`
	Dominance   float64   `bun:"dominance"`
	Date        time.Time `bun:"date,nullzero"`
	CreatedAt   time.Time `bun:"created_at,nullzero"`

	OpponentsDefeated
}

func (ts TribeSnapshot) ToDomain() (domain.TribeSnapshot, error) {
	od, err := ts.OpponentsDefeated.ToDomain()
	if err != nil {
		return domain.TribeSnapshot{}, fmt.Errorf(
			"couldn't construct domain.TribeSnapshot (id=%d): %w",
			ts.ID,
			err,
		)
	}

	converted, err := domain.UnmarshalTribeSnapshotFromDatabase(
		ts.ID,
		ts.TribeID,
		ts.ServerKey,
		ts.NumMembers,
		ts.NumVillages,
		ts.Points,
		ts.AllPoints,
		ts.Rank,
		od,
		ts.Dominance,
		ts.Date,
		ts.CreatedAt,
	)
	if err != nil {
		return domain.TribeSnapshot{}, fmt.Errorf(
			"couldn't construct domain.TribeSnapshot (id=%d): %w",
			ts.ID,
			err,
		)
	}

	return converted, nil
}

type TribeSnapshots []TribeSnapshot

func (tss TribeSnapshots) ToDomain() (domain.TribeSnapshots, error) {
	res := make(domain.TribeSnapshots, 0, len(tss))

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

		res = append(res, converted)
	}

	return res, nil
}
