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

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

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

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

	if err := repo.db.NewSelect().
		Model(&tribeSnapshots).
		Apply(listTribeSnapshotsParamsApplier{params: params}.apply).
		Relation("Tribe", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Column(bunmodel.TribeMetaColumns...)
		}).
		Scan(ctx); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return domain.ListTribeSnapshotsWithRelationsResult{}, fmt.Errorf(
			"couldn't select tribe snapshots from the db: %w",
			err,
		)
	}

	converted, err := tribeSnapshots.ToDomainWithRelations()
	if err != nil {
		return domain.ListTribeSnapshotsWithRelationsResult{}, err
	}

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

func (repo *TribeSnapshotBunRepository) Delete(ctx context.Context, serverKey string, dateLTE time.Time) error {
	if _, err := repo.db.NewDelete().
		Model(&bunmodel.TribeSnapshot{}).
		Where("server_key = ?", serverKey).
		Where("date <= ?", dateLTE).
		Returning("NULL").
		Exec(ctx); err != nil {
		return fmt.Errorf("couldn't delete tribe snapshots: %w", err)
	}

	return nil
}

type listTribeSnapshotsParamsApplier struct {
	params domain.ListTribeSnapshotsParams
}

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

	if tribeIDs := a.params.TribeIDs(); len(tribeIDs) > 0 {
		q = q.Where("ts.tribe_id IN (?)", bun.In(tribeIDs))
	}

	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.Limit(a.params.Limit() + 1).Apply(a.applyCursor)
}

func (a listTribeSnapshotsParamsApplier) 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.TribeSnapshotSortIDASC,
			domain.TribeSnapshotSortIDDESC:
			el.value = cursor.ID()
			el.unique = true
		case domain.TribeSnapshotSortServerKeyASC,
			domain.TribeSnapshotSortServerKeyDESC:
			el.value = cursor.ServerKey()
		case domain.TribeSnapshotSortDateASC,
			domain.TribeSnapshotSortDateDESC:
			el.value = cursor.Date()
		default:
			return q.Err(fmt.Errorf("%s: %w", s.String(), errInvalidSortValue))
		}

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

	return q.Apply(cursorApplier.apply)
}

func (a listTribeSnapshotsParamsApplier) sortToColumnAndDirection(
	s domain.TribeSnapshotSort,
) (bun.Safe, sortDirection, error) {
	switch s {
	case domain.TribeSnapshotSortDateASC:
		return "ts.date", sortDirectionASC, nil
	case domain.TribeSnapshotSortDateDESC:
		return "ts.date", sortDirectionDESC, nil
	case domain.TribeSnapshotSortIDASC:
		return "ts.id", sortDirectionASC, nil
	case domain.TribeSnapshotSortIDDESC:
		return "ts.id", sortDirectionDESC, nil
	case domain.TribeSnapshotSortServerKeyASC:
		return "ts.server_key", sortDirectionASC, nil
	case domain.TribeSnapshotSortServerKeyDESC:
		return "ts.server_key", sortDirectionDESC, nil
	default:
		return "", 0, fmt.Errorf("%s: %w", s.String(), errInvalidSortValue)
	}
}
