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.Servers, error) {
	var servers bunmodel.Servers

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

	return servers.ToDomain()
}

func (repo *ServerBunRepository) baseListQuery(params domain.ListServersParams) *bun.SelectQuery {
	return repo.db.NewSelect().Apply(listServersParamsApplier{params: params}.apply)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

	return q
}

type listServersParamsApplier struct {
	params domain.ListServersParams
}

//nolint:gocyclo
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 keyGT := a.params.KeyGT(); keyGT.Valid {
		q = q.Where("server.key > ?", keyGT.Value)
	}

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

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

	for _, s := range a.params.Sort() {
		switch s {
		case domain.ServerSortKeyASC:
			q = q.Order("server.key ASC")
		case domain.ServerSortKeyDESC:
			q = q.Order("server.key DESC")
		case domain.ServerSortOpenASC:
			q = q.Order("server.open ASC")
		case domain.ServerSortOpenDESC:
			q = q.Order("server.open DESC")
		default:
			return q.Err(errors.New("unsupported sort value"))
		}
	}

	return q.Limit(a.params.Limit()).Offset(a.params.Offset())
}
