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

func NewTribeBunRepository(db bun.IDB) *TribeBunRepository {
	return &TribeBunRepository{db: db}
}

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

	now := time.Now()
	tribes := make(bunmodel.Tribes, 0, len(params))

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

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

	//nolint:exhaustive
	switch q.Dialect().Name() {
	case dialect.PG:
		q = q.On("CONFLICT ON CONSTRAINT tribes_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("tag = EXCLUDED.tag").
		Set("num_members = EXCLUDED.num_members").
		Set("num_villages = EXCLUDED.num_villages").
		Set("points = EXCLUDED.points").
		Set("all_points = EXCLUDED.all_points").
		Set("rank = EXCLUDED.rank").
		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("deleted_at = EXCLUDED.deleted_at").
		Apply(appendODSetClauses).
		Returning("").
		Exec(ctx); err != nil {
		return fmt.Errorf("something went wrong while inserting tribes into the db: %w", err)
	}

	return nil
}

func (repo *TribeBunRepository) UpdateDominance(ctx context.Context, serverKey string, numPlayerVillages int) error {
	q := repo.db.NewUpdate().
		Model((*bunmodel.Tribe)(nil)).
		Returning("NULL").
		Where("server_key = ?", serverKey).
		Where("deleted_at IS NULL")

	if numPlayerVillages > 0 {
		q = q.Set("dominance = CAST(num_villages as double precision) / ? * 100", numPlayerVillages)
	} else {
		q = q.Set("dominance = 0")
	}

	if _, err := q.Exec(ctx); err != nil {
		return fmt.Errorf("%s: couldn't update dominance: %w", serverKey, err)
	}

	return nil
}

func (repo *TribeBunRepository) List(
	ctx context.Context,
	params domain.ListTribesParams,
) (domain.ListTribesResult, error) {
	var tribes bunmodel.Tribes

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

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

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

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

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

	return nil
}

type listTribesParamsApplier struct {
	params domain.ListTribesParams
}

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

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

	if tags := a.params.Tags(); len(tags) > 0 {
		q = q.Where("tribe.tag IN (?)", bun.In(tags))
	}

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

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

//nolint:gocyclo
func (a listTribesParamsApplier) 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.TribeSortIDASC,
			domain.TribeSortIDDESC:
			el.value = cursor.ID()
			el.unique = true
		case domain.TribeSortServerKeyASC,
			domain.TribeSortServerKeyDESC:
			el.value = cursor.ServerKey()
		case domain.TribeSortODScoreAttASC,
			domain.TribeSortODScoreAttDESC:
			el.value = cursor.ODScoreAtt()
		case domain.TribeSortODScoreDefASC,
			domain.TribeSortODScoreDefDESC:
			el.value = cursor.ODScoreDef()
		case domain.TribeSortODScoreTotalASC,
			domain.TribeSortODScoreTotalDESC:
			el.value = cursor.ODScoreTotal()
		case domain.TribeSortPointsASC,
			domain.TribeSortPointsDESC:
			el.value = cursor.Points()
		case domain.TribeSortDominanceASC,
			domain.TribeSortDominanceDESC:
			el.value = cursor.Dominance()
		case domain.TribeSortDeletedAtASC,
			domain.TribeSortDeletedAtDESC:
			el.value = cursor.DeletedAt()
		default:
			return q.Err(fmt.Errorf("%s: %w", s.String(), errInvalidSortValue))
		}

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

	return q.Apply(cursorApplier.apply)
}

//nolint:gocyclo
func (a listTribesParamsApplier) sortToColumnAndDirection(
	s domain.TribeSort,
) (bun.Safe, sortDirection, error) {
	switch s {
	case domain.TribeSortIDASC:
		return "tribe.id", sortDirectionASC, nil
	case domain.TribeSortIDDESC:
		return "tribe.id", sortDirectionDESC, nil
	case domain.TribeSortServerKeyASC:
		return "tribe.server_key", sortDirectionASC, nil
	case domain.TribeSortServerKeyDESC:
		return "tribe.server_key", sortDirectionDESC, nil
	case domain.TribeSortODScoreAttASC:
		return "tribe.score_att", sortDirectionASC, nil
	case domain.TribeSortODScoreAttDESC:
		return "tribe.score_att", sortDirectionDESC, nil
	case domain.TribeSortODScoreDefASC:
		return "tribe.score_def", sortDirectionASC, nil
	case domain.TribeSortODScoreDefDESC:
		return "tribe.score_def", sortDirectionDESC, nil
	case domain.TribeSortODScoreTotalASC:
		return "tribe.score_total", sortDirectionASC, nil
	case domain.TribeSortODScoreTotalDESC:
		return "tribe.score_total", sortDirectionDESC, nil
	case domain.TribeSortPointsASC:
		return "tribe.points", sortDirectionASC, nil
	case domain.TribeSortPointsDESC:
		return "tribe.points", sortDirectionDESC, nil
	case domain.TribeSortDominanceASC:
		return "tribe.dominance", sortDirectionASC, nil
	case domain.TribeSortDominanceDESC:
		return "tribe.dominance", sortDirectionDESC, nil
	case domain.TribeSortDeletedAtASC:
		return "COALESCE(tribe.deleted_at, '0001-01-01 00:00:00+00:00')", sortDirectionASC, nil
	case domain.TribeSortDeletedAtDESC:
		return "COALESCE(tribe.deleted_at, '0001-01-01 00:00:00+00:00')", sortDirectionDESC, nil
	default:
		return "", 0, fmt.Errorf("%s: %w", s.String(), errInvalidSortValue)
	}
}
