package apimodel

import (
	"gitea.dwysokinski.me/twhelp/corev3/internal/domain"
)

func NewPlayerOpponentsDefeated(od domain.OpponentsDefeated) PlayerOpponentsDefeated {
	return PlayerOpponentsDefeated{
		RankAtt:    od.RankAtt(),
		RankDef:    od.RankDef(),
		RankSup:    od.RankSup(),
		RankTotal:  od.RankTotal(),
		ScoreAtt:   od.ScoreAtt(),
		ScoreDef:   od.ScoreDef(),
		ScoreSup:   od.ScoreSup(),
		ScoreTotal: od.ScoreTotal(),
	}
}

func NewPlayer(p domain.Player) Player {
	converted := Player{
		BestRank:          p.BestRank(),
		BestRankAt:        p.BestRankAt(),
		CreatedAt:         p.CreatedAt(),
		Id:                p.ID(),
		LastActivityAt:    p.LastActivityAt(),
		MostPoints:        p.MostPoints(),
		MostPointsAt:      p.MostPointsAt(),
		MostVillages:      p.MostVillages(),
		MostVillagesAt:    p.MostVillagesAt(),
		Name:              p.Name(),
		NumVillages:       p.NumVillages(),
		OpponentsDefeated: NewPlayerOpponentsDefeated(p.OD()),
		Points:            p.Points(),
		ProfileUrl:        p.ProfileURL().String(),
		Rank:              p.Rank(),
	}

	if deletedAt := p.DeletedAt(); !deletedAt.IsZero() {
		converted.DeletedAt = &deletedAt
	}

	return converted
}

func NewListPlayersResponse(res domain.ListPlayersResult) ListPlayersResponse {
	players := res.Players()

	resp := ListPlayersResponse{
		Data: make([]Player, 0, len(players)),
		Cursor: Cursor{
			Next: res.Next().Encode(),
			Self: res.Self().Encode(),
		},
	}

	for _, p := range players {
		resp.Data = append(resp.Data, NewPlayer(p))
	}

	return resp
}
