package adapter

import (
	"context"
	"database/sql"
	"errors"
	"fmt"

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

	return ennoblements.ToDomain()
}

type listEnnoblementsParamsApplier struct {
	params domain.ListEnnoblementsParams
}

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

	for _, s := range a.params.Sort() {
		switch s {
		case domain.EnnoblementSortCreatedAtASC:
			q = q.Order("ennoblement.created_at ASC")
		case domain.EnnoblementSortCreatedAtDESC:
			q = q.Order("ennoblement.created_at DESC")
		case domain.EnnoblementSortIDASC:
			q = q.Order("ennoblement.id ASC")
		case domain.EnnoblementSortIDDESC:
			q = q.Order("ennoblement.id DESC")
		case domain.EnnoblementSortServerKeyASC:
			q = q.Order("ennoblement.server_key ASC")
		case domain.EnnoblementSortServerKeyDESC:
			q = q.Order("ennoblement.server_key DESC")
		default:
			return q.Err(errors.New("unsupported sort value"))
		}
	}

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