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 TribeChangeBunRepository struct {
	db bun.IDB
}

func NewTribeChangeBunRepository(db bun.IDB) *TribeChangeBunRepository {
	return &TribeChangeBunRepository{db: db}
}

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

	now := time.Now()
	tribeChanges := make(bunmodel.TribeChanges, 0, len(params))

	for _, p := range params {
		tribeChanges = append(tribeChanges, bunmodel.TribeChange{
			ServerKey:  p.ServerKey(),
			PlayerID:   p.PlayerID(),
			NewTribeID: p.NewTribeID(),
			OldTribeID: p.OldTribeID(),
			CreatedAt:  now,
		})
	}

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

	return nil
}

func (repo *TribeChangeBunRepository) List(
	ctx context.Context,
	params domain.ListTribeChangesParams,
) (domain.ListTribeChangesResult, error) {
	var tribeChanges bunmodel.TribeChanges

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

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

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

func (repo *TribeChangeBunRepository) ListWithRelations(
	ctx context.Context,
	params domain.ListTribeChangesParams,
) (domain.ListTribeChangesWithRelationsResult, error) {
	var tribeChanges bunmodel.TribeChanges

	if err := repo.db.NewSelect().
		Model(&tribeChanges).
		Apply(listTribeChangesParamsApplier{params: params}.apply).
		Relation("Player", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Column(bunmodel.PlayerMetaColumns...)
		}).
		Relation("NewTribe", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Column(bunmodel.TribeMetaColumns...)
		}).
		Relation("OldTribe", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Column(bunmodel.TribeMetaColumns...)
		}).
		Scan(ctx); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return domain.ListTribeChangesWithRelationsResult{}, fmt.Errorf("couldn't select tribe changes from the db: %w", err)
	}

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

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

type listTribeChangesParamsApplier struct {
	params domain.ListTribeChangesParams
}

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

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

	if tribeIDs := a.params.TribeIDs(); len(tribeIDs) > 0 {
		q = q.WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Where("tc.new_tribe_id IN (?)", bun.In(tribeIDs)).
				WhereOr("tc.old_tribe_id IN (?)", bun.In(tribeIDs))
		})
	}

	if since := a.params.Since(); since.Valid {
		q = q.Where("tc.created_at >= ?", since.V)
	}

	if before := a.params.Before(); before.Valid {
		q = q.Where("tc.created_at < ?", before.V)
	}

	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 listTribeChangesParamsApplier) 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.TribeChangeSortIDASC,
			domain.TribeChangeSortIDDESC:
			el.value = cursor.ID()
			el.unique = true
		case domain.TribeChangeSortServerKeyASC,
			domain.TribeChangeSortServerKeyDESC:
			el.value = cursor.ServerKey()
		case domain.TribeChangeSortCreatedAtASC,
			domain.TribeChangeSortCreatedAtDESC:
			el.value = cursor.CreatedAt()
		default:
			return q.Err(fmt.Errorf("%s: %w", s.String(), errInvalidSortValue))
		}

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

	return q.Apply(cursorApplier.apply)
}

func (a listTribeChangesParamsApplier) sortToColumnAndDirection(
	s domain.TribeChangeSort,
) (bun.Safe, sortDirection, error) {
	switch s {
	case domain.TribeChangeSortCreatedAtASC:
		return "tc.created_at", sortDirectionASC, nil
	case domain.TribeChangeSortCreatedAtDESC:
		return "tc.created_at", sortDirectionDESC, nil
	case domain.TribeChangeSortIDASC:
		return "tc.id", sortDirectionASC, nil
	case domain.TribeChangeSortIDDESC:
		return "tc.id", sortDirectionDESC, nil
	case domain.TribeChangeSortServerKeyASC:
		return "tc.server_key", sortDirectionASC, nil
	case domain.TribeChangeSortServerKeyDESC:
		return "tc.server_key", sortDirectionDESC, nil
	default:
		return "", 0, fmt.Errorf("%s: %w", s.String(), errInvalidSortValue)
	}
}
