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.TribeChanges, 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 nil, fmt.Errorf("couldn't select tribe changes from the db: %w", err)
	}

	return tribeChanges.ToDomain()
}

type listTribeChangesParamsApplier struct {
	params domain.ListTribeChangesParams
}

//nolint:gocyclo
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))
	}

	for _, s := range a.params.Sort() {
		switch s {
		case domain.TribeChangeSortCreatedAtASC:
			q = q.Order("tc.created_at ASC")
		case domain.TribeChangeSortCreatedAtDESC:
			q = q.Order("tc.created_at DESC")
		case domain.TribeChangeSortIDASC:
			q = q.Order("tc.id ASC")
		case domain.TribeChangeSortIDDESC:
			q = q.Order("tc.id DESC")
		case domain.TribeChangeSortServerKeyASC:
			q = q.Order("tc.server_key ASC")
		case domain.TribeChangeSortServerKeyDESC:
			q = q.Order("tc.server_key DESC")
		default:
			return q.Err(errors.New("unsupported sort value"))
		}
	}

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