package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/genex/translate-service/internal/application/service"
)

// TranslateHandler is the HTTP interface layer that delegates to the application service.
type TranslateHandler struct {
	svc *service.TranslateService
}

// NewTranslateHandler creates a new TranslateHandler.
func NewTranslateHandler(svc *service.TranslateService) *TranslateHandler {
	return &TranslateHandler{svc: svc}
}

// CreateMappingReq represents the request body for creating an address mapping.
type CreateMappingReq struct {
	UserID          string `json:"userId" binding:"required"`
	InternalAddress string `json:"internalAddress" binding:"required"`
	ChainAddress    string `json:"chainAddress" binding:"required"`
	ChainType       string `json:"chainType" binding:"required"`
}

// CreateMapping handles POST /api/v1/translate/mappings
func (h *TranslateHandler) CreateMapping(c *gin.Context) {
	var req CreateMappingReq
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": -1, "message": err.Error()})
		return
	}

	mapping, err := h.svc.CreateMapping(c.Request.Context(), req.UserID, req.InternalAddress, req.ChainAddress, req.ChainType)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": -1, "message": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 0, "data": mapping})
}

// Resolve handles GET /api/v1/translate/resolve
func (h *TranslateHandler) Resolve(c *gin.Context) {
	address := c.Query("address")
	direction := c.DefaultQuery("direction", "internal_to_chain")
	chain := c.DefaultQuery("chain", "")

	ctx := c.Request.Context()

	if direction == "internal_to_chain" {
		m, err := h.svc.InternalToChain(ctx, address)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"code": -1, "message": err.Error()})
			return
		}
		if m != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "data": m})
			return
		}
	} else {
		m, err := h.svc.ChainToInternal(ctx, chain, address)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"code": -1, "message": err.Error()})
			return
		}
		if m != nil {
			c.JSON(http.StatusOK, gin.H{"code": 0, "data": m})
			return
		}
	}

	c.JSON(http.StatusNotFound, gin.H{"code": -1, "message": "Address not found"})
}

// GetByUser handles GET /api/v1/translate/user/:userId
func (h *TranslateHandler) GetByUser(c *gin.Context) {
	userID := c.Param("userId")

	mappings, err := h.svc.GetByUserID(c.Request.Context(), userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": -1, "message": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 0, "data": mappings})
}
