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

func NewVersionBunRepository(db bun.IDB) *VersionBunRepository {
	return &VersionBunRepository{db: db}
}

func (repo *VersionBunRepository) List(ctx context.Context, params domain.ListVersionsParams) (domain.Versions, error) {
	var versions bunmodel.Versions

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

	return versions.ToDomain()
}

func (repo *VersionBunRepository) ListCount(
	ctx context.Context,
	params domain.ListVersionsParams,
) (domain.Versions, int, error) {
	versions, err := repo.List(ctx, params)
	if err != nil {
		return nil, 0, err
	}

	return versions, len(versions), nil
}

type listVersionsParamsApplier struct {
	params domain.ListVersionsParams
}

func (a listVersionsParamsApplier) apply(q *bun.SelectQuery) *bun.SelectQuery {
	for _, s := range a.params.Sort() {
		switch s {
		case domain.VersionSortCodeASC:
			q = q.Order("version.code ASC")
		case domain.VersionSortCodeDESC:
			q = q.Order("version.code DESC")
		default:
			return q.Err(errors.New("unsupported sort value"))
		}
	}

	return q
}
