package vclaim

import (
	"net/http"
	"time"

	pesertaService "service/internal/bpjs/vclaim/peserta"
	"service/pkg/errors"
	"service/pkg/response"

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

type PesertaHandler struct {
	service pesertaService.Service
}

func NewPesertaHandler(service pesertaService.Service) *PesertaHandler {
	return &PesertaHandler{service: service}
}

func (h *PesertaHandler) RegisterRoutes(router *gin.RouterGroup) {
	group := router.Group("/bpjs/vclaim/peserta")
	{
		group.GET("/nik/:nik", h.GetPesertaByNIK)
		group.GET("/nokartu/:nokartu", h.GetPesertaByNoKartu)
	}
}

func (h *PesertaHandler) GetPesertaByNIK(c *gin.Context) {
	nik := c.Param("nik")
	tglSEP := c.Query("tgl_sep")
	if tglSEP == "" {
		tglSEP = time.Now().Format("2006-01-02")
	}

	ctx := c.Request.Context()
	res, err := h.service.GetPesertaByNIK(ctx, nik, tglSEP)
	if err != nil {
		appErr := errors.FromError(err)
		response.Error(c, appErr.HTTPStatus(), appErr.Error(), appErr.Metadata())
		return
	}

	response.Success(c, http.StatusOK, "Successfully retrieved participant data by NIK", res)
}

func (h *PesertaHandler) GetPesertaByNoKartu(c *gin.Context) {
	noKartu := c.Param("nokartu")
	tglSEP := c.Query("tgl_sep")
	if tglSEP == "" {
		tglSEP = time.Now().Format("2006-01-02")
	}

	ctx := c.Request.Context()
	res, err := h.service.GetPesertaByNoKartu(ctx, noKartu, tglSEP)
	if err != nil {
		appErr := errors.FromError(err)
		response.Error(c, appErr.HTTPStatus(), appErr.Error(), appErr.Metadata())
		return
	}

	response.Success(c, http.StatusOK, "Successfully retrieved participant data by card number", res)
}
