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) PackageCreate(ctx context.Context, req *pb.PackageCreateReq, rsp *pb.PackageCreateRsp) error {
	h.logger.Debug(ctx, "PackagesCreate handler start")

	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.PackageCreate(ctx, req)
	if err != nil {
		h.logger.Error(ctx, "package create error", err)
		httpsrv.SetRspCode(ctx, http.StatusBadRequest)
		return httpsrv.SetError(NewValidationError(err))
	}

	rsp.Package = models.NewPackage(pkg)

	h.logger.Debug(ctx, "PackagesCreate handler stop")
	return nil
}
