package aplicare

import (
	"net/http"
	"strconv"

	bedService "service/internal/bpjs/aplicare/bed"
	"service/pkg/errors"
	"service/pkg/response"

	"github.com/gin-gonic/gin"
)

type BedHandler struct {
	service bedService.Service
}

func NewBedHandler(service bedService.Service) *BedHandler {
	return &BedHandler{service: service}
}

func (h *BedHandler) RegisterRoutes(router *gin.RouterGroup) {
	group := router.Group("/bpjs/aplicare/bed")
	{
		group.GET("/:kdppk/:start/:limit", h.GetBedList)
		group.POST("/:kdppk", h.CreateBed)
		group.PUT("/:kdppk", h.UpdateBed)
		group.DELETE("/:kdppk", h.DeleteBed)
	}
}

func (h *BedHandler) GetBedList(c *gin.Context) {
	kdPpk := c.Param("kdppk")
	start, _ := strconv.Atoi(c.Param("start"))
	limit, _ := strconv.Atoi(c.Param("limit"))

	ctx := c.Request.Context()
	res, err := h.service.GetBedList(ctx, kdPpk, start, limit)
	if err != nil {
		appErr := errors.FromError(err)
		response.Error(c, appErr.HTTPStatus(), appErr.Error(), appErr.Metadata())
		return
	}

	response.Success(c, http.StatusOK, "Successfully retrieved BPJS Aplicares bed list", res)
}

func (h *BedHandler) CreateBed(c *gin.Context) {
	kdPpk := c.Param("kdppk")
	var req bedService.BedData
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "Invalid request body", err.Error())
		return
	}

	ctx := c.Request.Context()
	if err := h.service.CreateBed(ctx, kdPpk, req); err != nil {
		appErr := errors.FromError(err)
		response.Error(c, appErr.HTTPStatus(), appErr.Error(), appErr.Metadata())
		return
	}

	response.Success(c, http.StatusCreated, "Successfully created BPJS Aplicares bed data", nil)
}

func (h *BedHandler) UpdateBed(c *gin.Context) {
	kdPpk := c.Param("kdppk")
	var req bedService.BedData
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "Invalid request body", err.Error())
		return
	}

	ctx := c.Request.Context()
	if err := h.service.UpdateBed(ctx, kdPpk, req); err != nil {
		appErr := errors.FromError(err)
		response.Error(c, appErr.HTTPStatus(), appErr.Error(), appErr.Metadata())
		return
	}

	response.Success(c, http.StatusOK, "Successfully updated BPJS Aplicares bed data", nil)
}

func (h *BedHandler) DeleteBed(c *gin.Context) {
	kdPpk := c.Param("kdppk")
	var req bedService.BedDeletePayload
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "Invalid request body", err.Error())
		return
	}

	ctx := c.Request.Context()
	if err := h.service.DeleteBed(ctx, kdPpk, req); err != nil {
		appErr := errors.FromError(err)
		response.Error(c, appErr.HTTPStatus(), appErr.Error(), appErr.Metadata())
		return
	}

	response.Success(c, http.StatusOK, "Successfully deleted BPJS Aplicares bed data", nil)
}
