package middleware

import (
	"context"
	"errors"
	"net/http"

	"codeberg.org/nextgo/dbots/internal/db"
	"codeberg.org/nextgo/dbots/internal/errorutil"
	"github.com/go-chi/chi/v5"
	"github.com/go-chi/render"
	"github.com/jackc/pgx/v5"
)

const botKey contextKey = "bot"

func BotContext(q *db.Queries) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			ctx := req.Context()
			botID := chi.URLParam(req, "botID")
			bot, err := q.GetBot(ctx, botID)
			if err != nil {
				if errors.Is(err, pgx.ErrNoRows) {
					render.Render(w, req, errorutil.ErrNotFound)
				} else {
					render.Render(w, req, errorutil.ErrInternal(err))
				}
				return
			}

			ctx = context.WithValue(ctx, botKey, bot)
			next.ServeHTTP(w, req.WithContext(ctx))
		})
	}
}

func GetBot(ctx context.Context) *db.Bot {
	bot, ok := ctx.Value(botKey).(*db.Bot)
	if !ok {
		return nil
	}

	return bot
}
