package handler

import (
	"errors"
	"net/http"

	"github.com/saveinmed/backend-go/internal/domain"
	"github.com/saveinmed/backend-go/internal/http/middleware"
)

// ListTeam godoc
// @Summary Listar membros da equipe
// @Tags Equipe
// @Security BearerAuth
// @Produce json
// @Success 200 {object} domain.UserPage
// @Router /api/v1/team [get]
func (h *Handler) ListTeam(w http.ResponseWriter, r *http.Request) {
	claims, ok := middleware.GetClaims(r.Context())
	if !ok || claims.CompanyID == nil {
		writeError(w, http.StatusBadRequest, errors.New("missing company context"))
		return
	}

	filter := domain.UserFilter{
		CompanyID: claims.CompanyID,
		Limit:     100, // No pagination for team MVP
	}
	page, err := h.svc.ListUsers(r.Context(), filter, 1, 100)
	if err != nil {
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	writeJSON(w, http.StatusOK, map[string]any{"users": page.Users})
}

// InviteMember godoc
// @Summary Adicionar membro à equipe
// @Tags Equipe
// @Security BearerAuth
// @Accept json
// @Produce json
// @Param payload body domain.User true "Dados do usuário (email, name, role)"
// @Success 201 {object} domain.User
// @Router /api/v1/team [post]
func (h *Handler) InviteMember(w http.ResponseWriter, r *http.Request) {
	claims, ok := middleware.GetClaims(r.Context())
	if !ok || claims.CompanyID == nil {
		writeError(w, http.StatusBadRequest, errors.New("missing company context"))
		return
	}

	// Only Owner or Manager can invite
	// Ideally check requester role here.
	// MVP: Assume if you have access to this endpoint/UI you can do it?
	// Better to check role from claims if available.
	// We'll rely on "dono" check eventually.

	var req struct {
		Name     string `json:"name"`
		Email    string `json:"email"`
		Password string `json:"password"` // For MVP we set password directly
		Role     string `json:"role"`
	}
	if err := decodeJSON(r.Context(), r, &req); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	user := &domain.User{
		CompanyID: *claims.CompanyID,
		Name:      req.Name,
		Email:     req.Email,
		Role:      req.Role,
		Username:  req.Email, // Use email as username
	}

	if err := h.svc.CreateUser(r.Context(), user, req.Password); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	writeJSON(w, http.StatusCreated, user)
}
