package handler

import (
	"context"
	"net/http"

	"git.unistack.org/unistack-org/pkgdash/internal/models"
	pb "git.unistack.org/unistack-org/pkgdash/proto"
	httpsrv "go.unistack.org/micro-server-http/v4"
	"go.unistack.org/micro/v4/logger"
)

func (h *Handler) ModuleList(ctx context.Context, req *pb.ModuleListReq, rsp *pb.ModuleListRsp) error {
	logger.Debug(ctx, "Start GetModule")

	err := req.Validate()
	if err != nil {
		logger.Error(ctx, "validate error", err)
		httpsrv.SetRspCode(ctx, http.StatusBadRequest)
		return httpsrv.SetError(NewValidationError(err))
	}

	modules, err := h.store.ModuleList(ctx, req)
	if err != nil {
		logger.Error(ctx, "module list error", err)
		httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
		return httpsrv.SetError(NewInternalError(err))
	}

	for _, mod := range modules {
		rsp.Modules = append(rsp.Modules, models.NewModule(mod))
	}
	logger.Debug(ctx, "Success finish getModule")
	return nil
}
