package auth

import (
	"net/http"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/api/dto"
)

// MobileSessionHandler owns account-scoped mobile login management.
type MobileSessionHandler struct {
	store MobileSessionStore
}

// List handles GET /api/v1/me/mobile-sessions.
// It returns the caller's bounded set of active QR-paired mobile logins.
func (handler *MobileSessionHandler) List(r api.AuthenticatedRequest) (api.Response, error) {
	sessions, err := handler.store.ListActiveMobileSessions(r.Context(), r.UserID())
	if err != nil {
		return api.Response{}, err
	}
	items := make([]dto.MobileSessionResponse, 0, len(sessions))
	for _, session := range sessions {
		items = append(items, dto.MobileSessionResponse{
			ID:             session.ID,
			DeviceName:     session.DeviceName,
			DevicePlatform: session.DevicePlatform,
			ExpiresAt:      session.ExpiresAt,
			CreatedAt:      session.CreatedAt,
		})
	}
	return api.OK(dto.MobileSessionListResponse{Items: items}), nil
}

// Revoke handles DELETE /api/v1/me/mobile-sessions/:sessionFamilyId.
// It revokes the selected family only when it belongs to the caller.
func (handler *MobileSessionHandler) Revoke(r api.AuthenticatedRequest) (api.Response, error) {
	sessionFamilyID := strings.TrimSpace(r.Gin.Param("sessionFamilyId"))
	if sessionFamilyID == "" {
		return api.Response{}, api.NewHTTPError(http.StatusBadRequest, "sessionFamilyId is required")
	}
	if err := handler.store.RevokeMobileSession(r.Context(), r.UserID(), sessionFamilyID); err != nil {
		return api.Response{}, err
	}
	return api.NoContent(), nil
}
