package meet

import (
	"log/slog"
	"net/http"

	"github.com/go-chi/chi/v5"

	"github.com/ultisuite/ulti-backend/internal/api/apiresponse"
	"github.com/ultisuite/ulti-backend/internal/api/apivalidate"
	"github.com/ultisuite/ulti-backend/internal/api/middleware"
	"github.com/ultisuite/ulti-backend/internal/auth"
	meetpkg "github.com/ultisuite/ulti-backend/internal/meet"
)

type Handler struct {
	svc    *Service
	logger *slog.Logger
}

func NewHandler(meetCfg *meetpkg.Config) *Handler {
	return &Handler{
		svc:    NewService(meetCfg),
		logger: slog.Default().With("component", "meet-api"),
	}
}

func (h *Handler) Routes() chi.Router {
	r := chi.NewRouter()
	r.Post("/rooms", h.CreateRoom)
	r.Post("/rooms/{roomID}/token", h.GetToken)
	return r
}

func meetUser(claims *auth.Claims) *meetpkg.UserInfo {
	return &meetpkg.UserInfo{
		ID:    claims.Sub,
		Name:  claims.Name,
		Email: claims.Email,
	}
}

func (h *Handler) CreateRoom(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())

	var req createRoomRequest
	if r.ContentLength != 0 {
		if err := apivalidate.DecodeJSON(w, r, maxRequestBody, &req); err != nil {
			return
		}
	}
	if verr := validateCreateRoom(&req); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}

	user := meetUser(claims)
	user.IsMod = true
	token, err := h.svc.CreateRoom(req.Name, user)
	if err != nil {
		h.logger.Error("create room token", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusCreated, token)
}

func (h *Handler) GetToken(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())
	roomID := chi.URLParam(r, "roomID")
	if verr := validateRoomID(roomID); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}

	user := meetUser(claims)
	user.IsMod = false

	token, err := h.svc.GetToken(roomID, user)
	if err != nil {
		h.logger.Error("get room token", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusOK, token)
}
