package adapter

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"time"

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

type PlayerBunRepository struct {
	db bun.IDB
}

func NewPlayerBunRepository(db bun.IDB) *PlayerBunRepository {
	return &PlayerBunRepository{db: db}
}

func (repo *PlayerBunRepository) CreateOrUpdate(ctx context.Context, params ...domain.CreatePlayerParams) error {
	if len(params) == 0 {
		return nil
	}

	now := time.Now()
	players := make(bunmodel.Players, 0, len(params))

	for _, p := range params {
		base := p.Base()
		players = append(players, bunmodel.Player{
			ID:                base.ID(),
			ServerKey:         p.ServerKey(),
			Name:              base.Name(),
			NumVillages:       base.NumVillages(),
			Points:            base.Points(),
			Rank:              base.Rank(),
			TribeID:           base.TribeID(),
			ProfileURL:        base.ProfileURL().String(),
			BestRank:          p.BestRank(),
			BestRankAt:        p.BestRankAt(),
			MostPoints:        p.MostPoints(),
			MostPointsAt:      p.MostPointsAt(),
			MostVillages:      p.MostVillages(),
			MostVillagesAt:    p.MostVillagesAt(),
			LastActivityAt:    p.LastActivityAt(),
			CreatedAt:         now,
			OpponentsDefeated: bunmodel.NewOpponentsDefeated(base.OD()),
		})
	}

	q := repo.db.NewInsert().
		Model(&players)

	//nolint:exhaustive
	switch q.Dialect().Name() {
	case dialect.PG:
		q = q.On("CONFLICT ON CONSTRAINT players_pkey DO UPDATE")
	case dialect.SQLite:
		q = q.On("CONFLICT(id, server_key) DO UPDATE")
	default:
		q = q.Err(errors.New("unsupported dialect"))
	}

	if _, err := q.
		Set("name = EXCLUDED.name").
		Set("num_villages = EXCLUDED.num_villages").
		Set("points = EXCLUDED.points").
		Set("rank = EXCLUDED.rank").
		Set("tribe_id = EXCLUDED.tribe_id").
		Set("profile_url = EXCLUDED.profile_url").
		Set("best_rank = EXCLUDED.best_rank").
		Set("best_rank_at = EXCLUDED.best_rank_at").
		Set("most_villages = EXCLUDED.most_villages").
		Set("most_villages_at = EXCLUDED.most_villages_at").
		Set("most_points = EXCLUDED.most_points").
		Set("most_points_at = EXCLUDED.most_points_at").
		Set("last_activity_at = EXCLUDED.last_activity_at").
		Set("deleted_at = EXCLUDED.deleted_at").
		Apply(appendODSetClauses).
		Returning("").
		Exec(ctx); err != nil {
		return fmt.Errorf("something went wrong while inserting players into the db: %w", err)
	}

	return nil
}

func (repo *PlayerBunRepository) List(
	ctx context.Context,
	params domain.ListPlayersParams,
) (domain.ListPlayersResult, error) {
	var players bunmodel.Players

	if err := repo.db.NewSelect().
		Model(&players).
		Apply(listPlayersParamsApplier{params: params}.apply).
		Scan(ctx); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return domain.ListPlayersResult{}, fmt.Errorf("couldn't select players from the db: %w", err)
	}

	converted, err := players.ToDomain()
	if err != nil {
		return domain.ListPlayersResult{}, err
	}

	return domain.NewListPlayersResult(separateListResultAndNext(converted, params.Limit()))
}

func (repo *PlayerBunRepository) ListWithRelations(
	ctx context.Context,
	params domain.ListPlayersParams,
) (domain.ListPlayersWithRelationsResult, error) {
	var players bunmodel.Players

	if err := repo.db.NewSelect().
		Model(&players).
		Apply(listPlayersParamsApplier{params: params}.apply).
		Relation("Tribe", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Column(bunmodel.TribeMetaColumns...)
		}).
		Scan(ctx); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return domain.ListPlayersWithRelationsResult{}, fmt.Errorf("couldn't select players from the db: %w", err)
	}

	converted, err := players.ToDomainWithRelations()
	if err != nil {
		return domain.ListPlayersWithRelationsResult{}, err
	}

	return domain.NewListPlayersWithRelationsResult(separateListResultAndNext(converted, params.Limit()))
}

func (repo *PlayerBunRepository) Delete(ctx context.Context, serverKey string, ids ...int) error {
	if len(ids) == 0 {
		return nil
	}

	if _, err := repo.db.NewUpdate().
		Model((*bunmodel.Player)(nil)).
		Where("deleted_at IS NULL").
		Where("id IN (?)", bun.In(ids)).
		Where("server_key = ?", serverKey).
		Set("deleted_at = ?", time.Now()).
		Set("tribe_id = NULL").
		Returning("").
		Exec(ctx); err != nil {
		return fmt.Errorf("couldn't delete players: %w", err)
	}

	return nil
}

type listPlayersParamsApplier struct {
	params domain.ListPlayersParams
}

//nolint:gocyclo
func (a listPlayersParamsApplier) apply(q *bun.SelectQuery) *bun.SelectQuery {
	if ids := a.params.IDs(); len(ids) > 0 {
		q = q.Where("player.id IN (?)", bun.In(ids))
	}

	if serverKeys := a.params.ServerKeys(); len(serverKeys) > 0 {
		q = q.Where("player.server_key IN (?)", bun.In(serverKeys))
	}

	if names := a.params.Names(); len(names) > 0 {
		q = q.Where("player.name IN (?)", bun.In(names))
	}

	if tribeIDs := a.params.TribeIDs(); len(tribeIDs) > 0 {
		q = q.Where("player.tribe_id IN (?)", bun.In(tribeIDs))
	}

	if deleted := a.params.Deleted(); deleted.Valid {
		if deleted.V {
			q = q.Where("player.deleted_at IS NOT NULL")
		} else {
			q = q.Where("player.deleted_at IS NULL")
		}
	}

	for _, s := range a.params.Sort() {
		switch s {
		case domain.PlayerSortIDASC:
			q = q.Order("player.id ASC")
		case domain.PlayerSortIDDESC:
			q = q.Order("player.id DESC")
		case domain.PlayerSortServerKeyASC:
			q = q.Order("player.server_key ASC")
		case domain.PlayerSortServerKeyDESC:
			q = q.Order("player.server_key DESC")
		case domain.PlayerSortODScoreAttASC:
			q = q.Order("player.score_att ASC")
		case domain.PlayerSortODScoreAttDESC:
			q = q.Order("player.score_att DESC")
		case domain.PlayerSortODScoreDefASC:
			q = q.Order("player.score_def ASC")
		case domain.PlayerSortODScoreDefDESC:
			q = q.Order("player.score_def DESC")
		case domain.PlayerSortODScoreSupASC:
			q = q.Order("player.score_sup ASC")
		case domain.PlayerSortODScoreSupDESC:
			q = q.Order("player.score_sup DESC")
		case domain.PlayerSortODScoreTotalASC:
			q = q.Order("player.score_total ASC")
		case domain.PlayerSortODScoreTotalDESC:
			q = q.Order("player.score_total DESC")
		case domain.PlayerSortPointsASC:
			q = q.Order("player.points ASC")
		case domain.PlayerSortPointsDESC:
			q = q.Order("player.points DESC")
		case domain.PlayerSortDeletedAtASC:
			q = q.OrderExpr("COALESCE(player.deleted_at, ?) ASC", time.Time{})
		case domain.PlayerSortDeletedAtDESC:
			q = q.OrderExpr("COALESCE(player.deleted_at, ?) DESC", time.Time{})
		default:
			return q.Err(fmt.Errorf("%s: %w", s.String(), errInvalidSortValue))
		}
	}

	return q.Limit(a.params.Limit() + 1).Apply(a.applyCursor)
}

//nolint:gocyclo
func (a listPlayersParamsApplier) applyCursor(q *bun.SelectQuery) *bun.SelectQuery {
	cursor := a.params.Cursor()

	if cursor.IsZero() {
		return q
	}

	sort := a.params.Sort()
	cursorApplier := cursorPaginationApplier{
		data: make([]cursorPaginationApplierDataElement, 0, len(sort)),
	}

	for _, s := range sort {
		var el cursorPaginationApplierDataElement

		switch s {
		case domain.PlayerSortIDASC:
			el.value = cursor.ID()
			el.unique = true
			el.column = "player.id"
			el.direction = sortDirectionASC
		case domain.PlayerSortIDDESC:
			el.value = cursor.ID()
			el.unique = true
			el.column = "player.id"
			el.direction = sortDirectionDESC
		case domain.PlayerSortServerKeyASC:
			el.value = cursor.ServerKey()
			el.column = "player.server_key"
			el.direction = sortDirectionASC
		case domain.PlayerSortServerKeyDESC:
			el.value = cursor.ServerKey()
			el.column = "player.server_key"
			el.direction = sortDirectionDESC
		case domain.PlayerSortODScoreAttASC:
			el.value = cursor.ODScoreAtt()
			el.column = "player.score_att"
			el.direction = sortDirectionASC
		case domain.PlayerSortODScoreAttDESC:
			el.value = cursor.ODScoreAtt()
			el.column = "player.score_att"
			el.direction = sortDirectionDESC
		case domain.PlayerSortODScoreDefASC:
			el.value = cursor.ODScoreDef()
			el.column = "player.score_def"
			el.direction = sortDirectionASC
		case domain.PlayerSortODScoreDefDESC:
			el.value = cursor.ODScoreDef()
			el.column = "player.score_def"
			el.direction = sortDirectionDESC
		case domain.PlayerSortODScoreSupASC:
			el.value = cursor.ODScoreSup()
			el.column = "player.score_sup"
			el.direction = sortDirectionASC
		case domain.PlayerSortODScoreSupDESC:
			el.value = cursor.ODScoreSup()
			el.column = "player.score_sup"
			el.direction = sortDirectionDESC
		case domain.PlayerSortODScoreTotalASC:
			el.value = cursor.ODScoreTotal()
			el.column = "player.score_total"
			el.direction = sortDirectionASC
		case domain.PlayerSortODScoreTotalDESC:
			el.value = cursor.ODScoreTotal()
			el.column = "player.score_total"
			el.direction = sortDirectionDESC
		case domain.PlayerSortPointsASC:
			el.value = cursor.Points()
			el.column = "player.points"
			el.direction = sortDirectionASC
		case domain.PlayerSortPointsDESC:
			el.value = cursor.Points()
			el.column = "player.points"
			el.direction = sortDirectionDESC
		case domain.PlayerSortDeletedAtASC:
			el.value = cursor.DeletedAt()
			el.column = "COALESCE(player.deleted_at, '0001-01-01 00:00:00+00:00')"
			el.direction = sortDirectionASC
		case domain.PlayerSortDeletedAtDESC:
			el.value = cursor.DeletedAt()
			el.column = "COALESCE(player.deleted_at, '0001-01-01 00:00:00+00:00')"
			el.direction = sortDirectionDESC
		default:
			return q.Err(fmt.Errorf("%s: %w", s.String(), errInvalidSortValue))
		}

		cursorApplier.data = append(cursorApplier.data, el)
	}

	return q.Apply(cursorApplier.apply)
}
