package handlers

import (
	"context"
	"net/http"
	"time"

	"git.haelnorr.com/h/golib/hws"
	"git.haelnorr.com/h/oslstats/internal/config"
	"git.haelnorr.com/h/oslstats/internal/db"
	"git.haelnorr.com/h/oslstats/internal/store"
	"github.com/uptrace/bun"
)

func IsUsernameUnique(
	server *hws.Server,
	conn *bun.DB,
	cfg *config.Config,
	store *store.Store,
) http.Handler {
	return http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			username := r.FormValue("username")
			ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
			defer cancel()
			tx, err := conn.BeginTx(ctx, nil)
			if err != nil {
				throwInternalServiceError(server, w, r, "Database transaction failed", err)
				return
			}
			defer tx.Rollback()
			unique, err := db.IsUsernameUnique(ctx, tx, username)
			if err != nil {
				throwInternalServiceError(server, w, r, "Database query failed", err)
				return
			}
			tx.Commit()
			if !unique {
				w.WriteHeader(http.StatusConflict)
			} else {
				w.WriteHeader(http.StatusOK)
			}
		},
	)
}
