package spindle

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/bluesky-social/indigo/atproto/syntax"
	"github.com/go-chi/chi/v5"
)

type adminReq struct {
	Did string `json:"did"`
}

func (s *Spindle) adminRouter() http.Handler {
	r := chi.NewRouter()
	r.Use(s.adminMiddleware)
	r.Post("/user/allow", s.handleAdminUserAllow)
	r.Post("/user/block", s.handleAdminUserBlock)
	return r
}

func (s *Spindle) adminMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		u, p, ok := r.BasicAuth()
		if !ok || u != "admin" || p != s.cfg.Server.AdminPassword {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func (s *Spindle) handleAdminUserAllow(w http.ResponseWriter, r *http.Request) {
	var req adminReq
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "bad request body", http.StatusBadRequest)
		return
	}
	did, err := syntax.ParseDID(req.Did)
	if err != nil {
		http.Error(w, fmt.Sprintf("invalid did: %v", err), http.StatusBadRequest)
		return
	}
	if err := s.db.AllowDid(did.String()); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (s *Spindle) handleAdminUserBlock(w http.ResponseWriter, r *http.Request) {
	var req adminReq
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "bad request body", http.StatusBadRequest)
		return
	}
	did, err := syntax.ParseDID(req.Did)
	if err != nil {
		http.Error(w, fmt.Sprintf("invalid did: %v", err), http.StatusBadRequest)
		return
	}
	if err := s.db.BlockDid(did.String()); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

