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

func NewEnnoblementBunRepository(db bun.IDB) *EnnoblementBunRepository {
	return &EnnoblementBunRepository{db: db}
}

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

	ennoblements := make(bunmodel.Ennoblements, 0, len(params))

	for _, p := range params {
		base := p.Base()
		ennoblements = append(ennoblements, bunmodel.Ennoblement{
			ServerKey:  p.ServerKey(),
			VillageID:  base.VillageID(),
			NewOwnerID: base.NewOwnerID(),
			NewTribeID: base.NewTribeID(),
			OldOwnerID: base.OldOwnerID(),
			OldTribeID: base.OldTribeID(),
			Points:     base.Points(),
			CreatedAt:  base.CreatedAt(),
		})
	}

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

	return nil
}

func (repo *EnnoblementBunRepository) List(
	ctx context.Context,
	params domain.ListEnnoblementsParams,
) (domain.ListEnnoblementsResult, error) {
	var ennoblements bunmodel.Ennoblements

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

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

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

func (repo *EnnoblementBunRepository) ListWithRelations(
	ctx context.Context,
	params domain.ListEnnoblementsParams,
) (domain.ListEnnoblementsWithRelationsResult, error) {
	var ennoblements bunmodel.Ennoblements

	if err := repo.db.NewSelect().
		Model(&ennoblements).
		Apply(listEnnoblementsParamsApplier{params: params}.apply).
		Relation("Village", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Column(bunmodel.VillageMetaColumns...)
		}).
		Relation("NewOwner", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Column(bunmodel.PlayerMetaColumns...)
		}).
		Relation("NewTribe", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Column(bunmodel.TribeMetaColumns...)
		}).
		Relation("OldOwner", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Column(bunmodel.PlayerMetaColumns...)
		}).
		Relation("OldTribe", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Column(bunmodel.TribeMetaColumns...)
		}).
		Scan(ctx); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return domain.ListEnnoblementsWithRelationsResult{}, fmt.Errorf("couldn't select ennoblements from the db: %w", err)
	}

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

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

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

	return nil
}

type listEnnoblementsParamsApplier struct {
	params domain.ListEnnoblementsParams
}

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

	if villageIDs := a.params.VillageIDs(); len(villageIDs) > 0 {
		q = q.Where("ennoblement.village_id IN (?)", bun.In(villageIDs))
	}

	if playerIDs := a.params.PlayerIDs(); len(playerIDs) > 0 {
		q = q.WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Where("ennoblement.new_owner_id IN (?)", bun.In(playerIDs)).
				WhereOr("ennoblement.old_owner_id IN (?)", bun.In(playerIDs))
		})
	}

	if tribeIDs := a.params.TribeIDs(); len(tribeIDs) > 0 {
		q = q.WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery {
			return q.Where("ennoblement.new_tribe_id IN (?)", bun.In(tribeIDs)).
				WhereOr("ennoblement.old_tribe_id IN (?)", bun.In(tribeIDs))
		})
	}

	if since := a.params.Since(); since.Valid {
		q = q.Where("ennoblement.created_at >= ?", since.V)
	}

	if before := a.params.Before(); before.Valid {
		q = q.Where("ennoblement.created_at < ?", before.V)
	}

	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 listEnnoblementsParamsApplier) 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.EnnoblementSortIDASC,
			domain.EnnoblementSortIDDESC:
			el.value = cursor.ID()
			el.unique = true
		case domain.EnnoblementSortServerKeyASC,
			domain.EnnoblementSortServerKeyDESC:
			el.value = cursor.ServerKey()
		case domain.EnnoblementSortCreatedAtASC,
			domain.EnnoblementSortCreatedAtDESC:
			el.value = cursor.CreatedAt()
		default:
			return q.Err(fmt.Errorf("%s: %w", s.String(), errInvalidSortValue))
		}

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

	return q.Apply(cursorApplier.apply)
}

func (a listEnnoblementsParamsApplier) sortToColumnAndDirection(
	s domain.EnnoblementSort,
) (bun.Safe, sortDirection, error) {
	switch s {
	case domain.EnnoblementSortCreatedAtASC:
		return "ennoblement.created_at", sortDirectionASC, nil
	case domain.EnnoblementSortCreatedAtDESC:
		return "ennoblement.created_at", sortDirectionDESC, nil
	case domain.EnnoblementSortIDASC:
		return "ennoblement.id", sortDirectionASC, nil
	case domain.EnnoblementSortIDDESC:
		return "ennoblement.id", sortDirectionDESC, nil
	case domain.EnnoblementSortServerKeyASC:
		return "ennoblement.server_key", sortDirectionASC, nil
	case domain.EnnoblementSortServerKeyDESC:
		return "ennoblement.server_key", sortDirectionDESC, nil
	default:
		return "", 0, fmt.Errorf("%s: %w", s.String(), errInvalidSortValue)
	}
}
