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

func NewTribeSnapshotBunRepository(db bun.IDB) *TribeSnapshotBunRepository {
	return &TribeSnapshotBunRepository{db: db}
}

func (repo *TribeSnapshotBunRepository) Create(ctx context.Context, params ...domain.CreateTribeSnapshotParams) error {
	if len(params) == 0 {
		return nil
	}

	now := time.Now()
	tribeSnapshots := make(bunmodel.TribeSnapshots, 0, len(params))

	for _, p := range params {
		tribeSnapshots = append(tribeSnapshots, bunmodel.TribeSnapshot{
			TribeID:           p.TribeID(),
			ServerKey:         p.ServerKey(),
			NumMembers:        p.NumMembers(),
			NumVillages:       p.NumVillages(),
			Points:            p.Points(),
			AllPoints:         p.AllPoints(),
			Rank:              p.Rank(),
			Dominance:         p.Dominance(),
			Date:              p.Date(),
			CreatedAt:         now,
			OpponentsDefeated: bunmodel.NewOpponentsDefeated(p.OD()),
		})
	}

	if _, err := repo.db.NewInsert().
		Model(&tribeSnapshots).
		Ignore().
		Returning("").
		Exec(ctx); err != nil {
		return fmt.Errorf("something went wrong while inserting tribe snapshots into the db: %w", err)
	}

	return nil
}

func (repo *TribeSnapshotBunRepository) List(
	ctx context.Context,
	params domain.ListTribeSnapshotsParams,
) (domain.TribeSnapshots, error) {
	var tribeSnapshots bunmodel.TribeSnapshots

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

	return tribeSnapshots.ToDomain()
}

type listTribeSnapshotsParamsApplier struct {
	params domain.ListTribeSnapshotsParams
}

//nolint:gocyclo
func (a listTribeSnapshotsParamsApplier) apply(q *bun.SelectQuery) *bun.SelectQuery {
	if serverKeys := a.params.ServerKeys(); len(serverKeys) > 0 {
		q = q.Where("ts.server_key IN (?)", bun.In(serverKeys))
	}

	for _, s := range a.params.Sort() {
		switch s {
		case domain.TribeSnapshotSortDateASC:
			q = q.Order("ts.date ASC")
		case domain.TribeSnapshotSortDateDESC:
			q = q.Order("ts.date DESC")
		case domain.TribeSnapshotSortIDASC:
			q = q.Order("ts.id ASC")
		case domain.TribeSnapshotSortIDDESC:
			q = q.Order("ts.id DESC")
		case domain.TribeSnapshotSortServerKeyASC:
			q = q.Order("ts.server_key ASC")
		case domain.TribeSnapshotSortServerKeyDESC:
			q = q.Order("ts.server_key DESC")
		default:
			return q.Err(fmt.Errorf("%s: %w", s.String(), errInvalidSortValue))
		}
	}

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