package handler

import (
	"context"
	"net/http"

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

func (h *Handler) PackageUpdate(ctx context.Context, req *pb.PackageUpdateReq, rsp *pb.PackageUpdateRsp) error {
	h.logger.Debug(ctx, "Start UpdatePackage")

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

	pkg, err := h.store.PackageUpdate(ctx, req)
	if err != nil {
		h.logger.Error(ctx, "package update error", err)
		httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
		return httpsrv.SetError(NewInternalError(err))
	}

	rsp.Package = models.NewPackage(pkg)

	h.logger.Debug(ctx, "Success finish UpdatePackage")
	return nil
}
