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

func NewVillageBunRepository(db bun.IDB) *VillageBunRepository {
	return &VillageBunRepository{db: db}
}

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

	now := time.Now()
	villages := make(bunmodel.Villages, 0, len(params))

	for _, p := range params {
		base := p.Base()
		villages = append(villages, bunmodel.Village{
			ID:         base.ID(),
			ServerKey:  p.ServerKey(),
			Name:       base.Name(),
			Points:     base.Points(),
			X:          base.X(),
			Y:          base.Y(),
			Continent:  base.Continent(),
			Bonus:      base.Bonus(),
			PlayerID:   base.PlayerID(),
			ProfileURL: base.ProfileURL().String(),
			CreatedAt:  now,
		})
	}

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

	//nolint:exhaustive
	switch q.Dialect().Name() {
	case dialect.PG:
		q = q.On("CONFLICT ON CONSTRAINT villages_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("points = EXCLUDED.points").
		Set("x = EXCLUDED.x").
		Set("y = EXCLUDED.y").
		Set("continent = EXCLUDED.continent").
		Set("bonus = EXCLUDED.bonus").
		Set("player_id = EXCLUDED.player_id").
		Set("profile_url = EXCLUDED.profile_url").
		Returning("").
		Exec(ctx); err != nil {
		return fmt.Errorf("something went wrong while inserting villages into the db: %w", err)
	}

	return nil
}

func (repo *VillageBunRepository) List(ctx context.Context, params domain.ListVillagesParams) (domain.Villages, error) {
	var villages bunmodel.Villages

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

	return villages.ToDomain()
}

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

	if _, err := repo.db.NewDelete().
		Model((*bunmodel.Village)(nil)).
		Where("id IN (?)", bun.In(ids)).
		Where("server_key = ?", serverKey).
		Returning("").
		Exec(ctx); err != nil {
		return fmt.Errorf("couldn't delete villages: %w", err)
	}

	return nil
}

type listVillagesParamsApplier struct {
	params domain.ListVillagesParams
}

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

	if idGT := a.params.IDGT(); idGT.Valid {
		q = q.Where("village.id > ?", idGT.Value)
	}

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

	for _, s := range a.params.Sort() {
		switch s {
		case domain.VillageSortIDASC:
			q = q.Order("village.id ASC")
		case domain.VillageSortIDDESC:
			q = q.Order("village.id DESC")
		case domain.VillageSortServerKeyASC:
			q = q.Order("village.server_key ASC")
		case domain.VillageSortServerKeyDESC:
			q = q.Order("village.server_key DESC")
		default:
			return q.Err(errors.New("unsupported sort value"))
		}
	}

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