package logic

import (
	"context"
	"errors"

	"juwan-backend/app/review/rpc/internal/svc"
	"juwan-backend/app/review/rpc/pb"
	"juwan-backend/app/snowflake/rpc/snowflake"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddReviewsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddReviewsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddReviewsLogic {
	return &AddReviewsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddReviewsLogic) AddReviews(in *pb.AddReviewsReq) (*pb.AddReviewsResp, error) {
	if in.GetOrderId() <= 0 {
		return nil, errors.New("orderId is required")
	}
	if in.GetFromUserId() <= 0 {
		return nil, errors.New("fromUserId is required")
	}
	if in.GetToUserId() <= 0 {
		return nil, errors.New("toUserId is required")
	}
	if in.GetRating() < 1 || in.GetRating() > 5 {
		return nil, errors.New("rating must be between 1 and 5")
	}

	idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
	if err != nil {
		return nil, errors.New("create review id failed")
	}

	created, err := l.svcCtx.ReviewModelRW.Reviews.Create().
		SetID(idResp.Id).
		SetOrderID(in.GetOrderId()).
		SetFromUserID(in.GetFromUserId()).
		SetFromUserName(in.GetFromUserName()).
		SetFromUserAvatar(in.GetFromUserAvatar()).
		SetToUserID(in.GetToUserId()).
		SetRating(int16(in.GetRating())).
		SetContent(in.GetContent()).
		SetSealed(in.GetSealed()).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("addReviews err: %v", err)
		return nil, errors.New("add review failed")
	}

	return &pb.AddReviewsResp{Id: created.ID}, nil
}
