package handlers

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

	"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
	"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/service"

	"go.uber.org/zap"
)

// AuthHandler handles authentication requests
type AuthHandler struct {
	logger      *zap.Logger
	authService *service.AuthService
}

// NewAuthHandler creates a new auth handler
func NewAuthHandler(logger *zap.Logger, authService *service.AuthService) *AuthHandler {
	return &AuthHandler{
		logger:      logger,
		authService: authService,
	}
}

// Login handles user login
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
	// Parse login request
	var req models.LoginRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		h.logger.Error("Failed to parse login request", zap.Error(err))
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	// Authenticate user
	response, err := h.authService.Login(req.Email, req.Password)
	if err != nil {
		h.logger.Warn("Login failed", zap.Error(err), zap.String("email", req.Email))
		http.Error(w, "Invalid credentials", http.StatusUnauthorized)
		return
	}

	// Return tokens and user info
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(response)
}

// RefreshToken handles token refresh
func (h *AuthHandler) RefreshToken(w http.ResponseWriter, r *http.Request) {
	// Parse refresh token request
	var req models.RefreshRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		h.logger.Error("Failed to parse refresh token request", zap.Error(err))
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	// Refresh token
	accessToken, err := h.authService.RefreshToken(req.RefreshToken)
	if err != nil {
		h.logger.Warn("Token refresh failed", zap.Error(err))
		http.Error(w, "Invalid refresh token", http.StatusUnauthorized)
		return
	}

	// Return new access token
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(models.RefreshResponse{
		AccessToken: accessToken,
	})
}

// Logout handles user logout
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
	// In a real implementation, you would invalidate the refresh token
	// For now, just return a success message

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]string{
		"message": "Successfully logged out",
	})
}
