package auth

import (
	"context"

	"github.com/jackc/pgx/v5/pgtype"

	"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)

type ctxKey int

const (
	userCtxKey      ctxKey = 1
	sessionIDCtxKey ctxKey = 2
)

// UserFromContext returns the authenticated user placed in context by
// RequireUser. Returns false when RequireUser has not run (e.g. in tests that
// bypass the middleware, or programmer-error routing).
func UserFromContext(ctx context.Context) (dbq.User, bool) {
	u, ok := ctx.Value(userCtxKey).(dbq.User)
	return u, ok
}

// SessionIDFromContext returns the id of the session that authenticated this
// request. The active-sessions surface needs it for the two things it can't
// do from the user alone: mark which row is "this device", and exclude that
// row from "log out everywhere else" so the action doesn't sign the caller
// out of the page they invoked it from.
func SessionIDFromContext(ctx context.Context) (pgtype.UUID, bool) {
	id, ok := ctx.Value(sessionIDCtxKey).(pgtype.UUID)
	return id, ok
}
