package devices

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

	"github.com/go-chi/chi/v5"
	"github.com/wangjia/pangolin/server/internal/apierr"
)

// Handler serves the account device endpoints. It assumes the JWT auth
// middleware (module #2) has set CtxKeyUserID on the request context.
type Handler struct {
	svc *Service
}

// NewHandler creates a Handler backed by svc.
func NewHandler(svc *Service) *Handler { return &Handler{svc: svc} }

// RegisterRoutes mounts the device routes on r under the caller's chosen prefix
// (the API mounts these beneath /v1/me):
//
//	GET    /devices
//	DELETE /devices/{id}
func (h *Handler) RegisterRoutes(r chi.Router) {
	r.Get("/devices", h.ListDevices)
	r.Delete("/devices/{id}", h.DeleteDevice)
}

type listDevicesResponse struct {
	Devices []Device `json:"devices"`
}

// ListDevices handles GET /v1/me/devices.
func (h *Handler) ListDevices(w http.ResponseWriter, r *http.Request) {
	userID, ok := UserIDFromContext(r.Context())
	if !ok {
		apierr.WriteJSON(w, http.StatusUnauthorized, apierr.ErrUnauthorized)
		return
	}

	devices, apiErr := h.svc.ListDevices(r.Context(), userID)
	if apiErr != nil {
		apierr.WriteJSON(w, StatusForError(apiErr), apiErr)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	_ = json.NewEncoder(w).Encode(listDevicesResponse{Devices: devices})
}

// DeleteDevice handles DELETE /v1/me/devices/{id}.
func (h *Handler) DeleteDevice(w http.ResponseWriter, r *http.Request) {
	userID, ok := UserIDFromContext(r.Context())
	if !ok {
		apierr.WriteJSON(w, http.StatusUnauthorized, apierr.ErrUnauthorized)
		return
	}

	deviceUUID := chi.URLParam(r, "id")
	if apiErr := h.svc.DeleteDevice(r.Context(), userID, deviceUUID); apiErr != nil {
		apierr.WriteJSON(w, StatusForError(apiErr), apiErr)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
