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

func NewServerBunRepository(db bun.IDB) *ServerBunRepository {
	return &ServerBunRepository{db: db}
}

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

	now := time.Now()
	servers := make(bunmodel.Servers, 0, len(params))

	for _, p := range params {
		base := p.Base()
		servers = append(servers, bunmodel.Server{
			Key:         base.Key(),
			URL:         base.URL().String(),
			Open:        base.Open(),
			VersionCode: p.VersionCode(),
			CreatedAt:   now,
		})
	}

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

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

	if _, err := q.
		Set("url = EXCLUDED.url").
		Set("open = EXCLUDED.open").
		Returning("").
		Exec(ctx); err != nil {
		return fmt.Errorf("something went wrong while inserting servers into the db: %w", err)
	}

	return nil
}

func (repo *ServerBunRepository) List(
	ctx context.Context,
	params domain.ListServersParams,
) (domain.ListServersResult, error) {
	var servers bunmodel.Servers

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

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

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

func (repo *ServerBunRepository) Update(ctx context.Context, key string, params domain.UpdateServerParams) error {
	if params.IsZero() {
		return errors.New("nothing to update")
	}

	res, err := repo.db.NewUpdate().
		Model(&bunmodel.Server{}).
		Where("key = ?", key).
		Apply(updateServerParamsApplier{params: params}.apply).
		Returning("").
		Exec(ctx)
	if err != nil {
		return fmt.Errorf("%s: couldn't update server: %w", key, err)
	}
	if affected, _ := res.RowsAffected(); affected == 0 {
		return domain.ServerNotFoundError{
			Key: key,
		}
	}

	return nil
}

type updateServerParamsApplier struct {
	params domain.UpdateServerParams
}

//nolint:gocyclo
func (a updateServerParamsApplier) apply(q *bun.UpdateQuery) *bun.UpdateQuery {
	if config := a.params.Config(); config.Valid {
		q = q.Set("config = ?", bunmodel.NewServerConfig(config.V))
	}

	if unitInfo := a.params.UnitInfo(); unitInfo.Valid {
		q = q.Set("unit_info = ?", bunmodel.NewUnitInfo(unitInfo.V))
	}

	if buildingInfo := a.params.BuildingInfo(); buildingInfo.Valid {
		q = q.Set("building_info = ?", bunmodel.NewBuildingInfo(buildingInfo.V))
	}

	if numTribes := a.params.NumTribes(); numTribes.Valid {
		q = q.Set("num_tribes = ?", numTribes.V)
	}

	if tribeDataSyncedAt := a.params.TribeDataSyncedAt(); tribeDataSyncedAt.Valid {
		// TODO: rename this column to tribe_data_synced_at
		q = q.Set("tribe_data_updated_at = ?", tribeDataSyncedAt.V)
	}

	if numPlayers := a.params.NumPlayers(); numPlayers.Valid {
		q = q.Set("num_players = ?", numPlayers.V)
	}

	if playerDataSyncedAt := a.params.PlayerDataSyncedAt(); playerDataSyncedAt.Valid {
		// TODO: rename this column to player_data_synced_at
		q = q.Set("player_data_updated_at = ?", playerDataSyncedAt.V)
	}

	if numVillages := a.params.NumVillages(); numVillages.Valid {
		q = q.Set("num_villages = ?", numVillages.V)
	}

	if numPlayerVillages := a.params.NumPlayerVillages(); numPlayerVillages.Valid {
		q = q.Set("num_player_villages = ?", numPlayerVillages.V)
	}

	if numBarbarianVillages := a.params.NumBarbarianVillages(); numBarbarianVillages.Valid {
		q = q.Set("num_barbarian_villages = ?", numBarbarianVillages.V)
	}

	if numBonusVillages := a.params.NumBonusVillages(); numBonusVillages.Valid {
		q = q.Set("num_bonus_villages = ?", numBonusVillages.V)
	}

	if villageDataSyncedAt := a.params.VillageDataSyncedAt(); villageDataSyncedAt.Valid {
		// TODO: rename this column to village_data_synced_at
		q = q.Set("village_data_updated_at = ?", villageDataSyncedAt.V)
	}

	if ennoblementDataSyncedAt := a.params.EnnoblementDataSyncedAt(); ennoblementDataSyncedAt.Valid {
		// TODO: rename this column to ennoblement_data_synced_at
		q = q.Set("ennoblement_data_updated_at = ?", ennoblementDataSyncedAt.V)
	}

	if tribeSnapshotsCreatedAt := a.params.TribeSnapshotsCreatedAt(); tribeSnapshotsCreatedAt.Valid {
		q = q.Set("tribe_snapshots_created_at = ?", tribeSnapshotsCreatedAt.V)
	}

	if playerSnapshotsCreatedAt := a.params.PlayerSnapshotsCreatedAt(); playerSnapshotsCreatedAt.Valid {
		q = q.Set("player_snapshots_created_at = ?", playerSnapshotsCreatedAt.V)
	}

	return q
}

type listServersParamsApplier struct {
	params domain.ListServersParams
}

func (a listServersParamsApplier) apply(q *bun.SelectQuery) *bun.SelectQuery {
	if keys := a.params.Keys(); len(keys) > 0 {
		q = q.Where("server.key IN (?)", bun.In(keys))
	}

	if versionCodes := a.params.VersionCodes(); len(versionCodes) > 0 {
		q = q.Where("server.version_code IN (?)", bun.In(versionCodes))
	}

	if open := a.params.Open(); open.Valid {
		q = q.Where("server.open = ?", open.V)
	}

	if special := a.params.Special(); special.Valid {
		q = q.Where("server.special = ?", special.V)
	}

	if tribeSnapshotsCreatedAtLT := a.params.TribeSnapshotsCreatedAtLT(); tribeSnapshotsCreatedAtLT.Valid {
		q = q.Where(
			"server.tribe_snapshots_created_at < ? OR server.tribe_snapshots_created_at is null",
			tribeSnapshotsCreatedAtLT.V,
		)
	}

	if playerSnapshotsCreatedAtLT := a.params.PlayerSnapshotsCreatedAtLT(); playerSnapshotsCreatedAtLT.Valid {
		q = q.Where(
			"server.player_snapshots_created_at < ? OR server.player_snapshots_created_at is null",
			playerSnapshotsCreatedAtLT.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.Apply(a.applyCursor).Limit(a.params.Limit() + 1)
}

func (a listServersParamsApplier) 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.ServerSortKeyASC,
			domain.ServerSortKeyDESC:
			el.value = cursor.Key()
			el.unique = true
		case domain.ServerSortOpenASC,
			domain.ServerSortOpenDESC:
			el.value = cursor.Open()
		default:
			return q.Err(fmt.Errorf("%s: %w", s.String(), errInvalidSortValue))
		}

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

	return q.Apply(cursorApplier.apply)
}

func (a listServersParamsApplier) sortToColumnAndDirection(
	s domain.ServerSort,
) (bun.Safe, sortDirection, error) {
	switch s {
	case domain.ServerSortKeyASC:
		return "server.key", sortDirectionASC, nil
	case domain.ServerSortKeyDESC:
		return "server.key", sortDirectionDESC, nil
	case domain.ServerSortOpenASC:
		return "server.open", sortDirectionASC, nil
	case domain.ServerSortOpenDESC:
		return "server.open", sortDirectionDESC, nil
	default:
		return "", 0, fmt.Errorf("%s: %w", s.String(), errInvalidSortValue)
	}
}
