package logic

import (
	"context"
	"errors"
	"time"

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

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

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

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

// -----------------------orderStateLogs-----------------------
func (l *AddOrderStateLogsLogic) AddOrderStateLogs(in *pb.AddOrderStateLogsReq) (*pb.AddOrderStateLogsResp, error) {
	if in == nil {
		return nil, errors.New("order state log is required")
	}

	idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
	if err != nil {
		return nil, err
	}

	builder := l.svcCtx.OrderModelsRW.OrderStateLogs.Create().
		SetID(idResp.Id).
		SetOrderID(in.OrderId).
		SetToStatus(in.ToStatus).
		SetAction(in.Action).
		SetActorID(in.ActorId).
		SetActorRole(in.ActorRole)

	if in.FromStatus != nil {
		builder = builder.SetFromStatus(*in.FromStatus)
	}
	if in.Metadata != nil {
		metadata, err := parseJSONMap(*in.Metadata)
		if err != nil {
			return nil, err
		}
		builder = builder.SetMetadata(metadata)
	}
	if in.CreatedAt != nil {
		builder = builder.SetCreatedAt(time.Unix(*in.CreatedAt, 0))
	}

	if _, err := builder.Save(l.ctx); err != nil {
		return nil, err
	}

	return &pb.AddOrderStateLogsResp{}, nil
}
