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"
)

type PlayerSnapshotBunRepository struct {
	db bun.IDB
}

func NewPlayerSnapshotBunRepository(db bun.IDB) *PlayerSnapshotBunRepository {
	return &PlayerSnapshotBunRepository{db: db}
}

func (repo *PlayerSnapshotBunRepository) Create(
	ctx context.Context,
	params ...domain.CreatePlayerSnapshotParams,
) error {
	if len(params) == 0 {
		return nil
	}

	now := time.Now()
	playerSnapshots := make(bunmodel.PlayerSnapshots, 0, len(params))

	for _, p := range params {
		playerSnapshots = append(playerSnapshots, bunmodel.PlayerSnapshot{
			PlayerID:          p.PlayerID(),
			NumVillages:       p.NumVillages(),
			Points:            p.Points(),
			Rank:              p.Rank(),
			TribeID:           p.TribeID(),
			ServerKey:         p.ServerKey(),
			Date:              p.Date(),
			CreatedAt:         now,
			OpponentsDefeated: bunmodel.NewOpponentsDefeated(p.OD()),
		})
	}

	if _, err := repo.db.NewInsert().
		Model(&playerSnapshots).
		Ignore().
		Returning("").
		Exec(ctx); err != nil {
		return fmt.Errorf("something went wrong while inserting player snapshots into the db: %w", err)
	}

	return nil
}

func (repo *PlayerSnapshotBunRepository) List(
	ctx context.Context,
	params domain.ListPlayerSnapshotsParams,
) (domain.ListPlayerSnapshotsResult, error) {
	var playerSnapshots bunmodel.PlayerSnapshots

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

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

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

func (repo *PlayerSnapshotBunRepository) ListWithRelations(
	ctx context.Context,
	params domain.ListPlayerSnapshotsParams,
) (domain.ListPlayerSnapshotsWithRelationsResult, error) {
	var playerSnapshots bunmodel.PlayerSnapshots

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

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

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

func (repo *PlayerSnapshotBunRepository) Delete(ctx context.Context, serverKey string, dateLTE time.Time) error {
	if _, err := repo.db.NewDelete().
		Model(&bunmodel.PlayerSnapshot{}).
		Where("server_key = ?", serverKey).
		Where("date <= ?", dateLTE).
		Returning("NULL").
		Exec(ctx); err != nil {
		return fmt.Errorf("couldn't delete player snapshots: %w", err)
	}

	return nil
}

type listPlayerSnapshotsParamsApplier struct {
	params domain.ListPlayerSnapshotsParams
}

func (a listPlayerSnapshotsParamsApplier) apply(q *bun.SelectQuery) *bun.SelectQuery {
	if serverKeys := a.params.ServerKeys(); len(serverKeys) > 0 {
		q = q.Where("ps.server_key IN (?)", bun.In(serverKeys))
	}

	if playerIDs := a.params.PlayerIDs(); len(playerIDs) > 0 {
		q = q.Where("ps.player_id IN (?)", bun.In(playerIDs))
	}

	for _, s := range a.params.Sort() {
		column, dir, err := a.sortToColumnAndDirection(s)
		if err != nil {
			return q.Err(err)
		}

		q.OrderExpr("? ?", column, dir.Bun())
	}

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

func (a listPlayerSnapshotsParamsApplier) 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 err error
		var el cursorPaginationApplierDataElement

		el.column, el.direction, err = a.sortToColumnAndDirection(s)
		if err != nil {
			return q.Err(err)
		}

		switch s {
		case domain.PlayerSnapshotSortIDASC,
			domain.PlayerSnapshotSortIDDESC:
			el.value = cursor.ID()
			el.unique = true
		case domain.PlayerSnapshotSortServerKeyASC,
			domain.PlayerSnapshotSortServerKeyDESC:
			el.value = cursor.ServerKey()
		case domain.PlayerSnapshotSortDateASC,
			domain.PlayerSnapshotSortDateDESC:
			el.value = cursor.Date()
		default:
			return q.Err(fmt.Errorf("%s: %w", s.String(), errInvalidSortValue))
		}

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

	return q.Apply(cursorApplier.apply)
}

func (a listPlayerSnapshotsParamsApplier) sortToColumnAndDirection(
	s domain.PlayerSnapshotSort,
) (bun.Safe, sortDirection, error) {
	switch s {
	case domain.PlayerSnapshotSortDateASC:
		return "ps.date", sortDirectionASC, nil
	case domain.PlayerSnapshotSortDateDESC:
		return "ps.date", sortDirectionDESC, nil
	case domain.PlayerSnapshotSortIDASC:
		return "ps.id", sortDirectionASC, nil
	case domain.PlayerSnapshotSortIDDESC:
		return "ps.id", sortDirectionDESC, nil
	case domain.PlayerSnapshotSortServerKeyASC:
		return "ps.server_key", sortDirectionASC, nil
	case domain.PlayerSnapshotSortServerKeyDESC:
		return "ps.server_key", sortDirectionDESC, nil
	default:
		return "", 0, fmt.Errorf("%s: %w", s.String(), errInvalidSortValue)
	}
}
