package logic

import (
	"encoding/json"
	"errors"
	"time"

	"juwan-backend/app/order/rpc/internal/models"
	"juwan-backend/app/order/rpc/pb"

	"github.com/shopspring/decimal"
)

func parseDecimal(v string) (decimal.Decimal, error) {
	if v == "" {
		return decimal.Zero, nil
	}
	d, err := decimal.NewFromString(v)
	if err != nil {
		return decimal.Zero, errors.New("invalid decimal value")
	}
	return d, nil
}

func parseJSONMap(v string) (map[string]any, error) {
	if v == "" {
		return map[string]any{}, nil
	}
	var result map[string]any
	if err := json.Unmarshal([]byte(v), &result); err != nil {
		return nil, errors.New("invalid json value")
	}
	if result == nil {
		return map[string]any{}, nil
	}
	return result, nil
}

func unixPtr(v *int64) *time.Time {
	if v == nil || *v <= 0 {
		return nil
	}
	t := time.Unix(*v, 0)
	return &t
}

func toPBOrder(item *models.Orders) *pb.Orders {
	serviceSnapshot := "{}"
	if b, err := json.Marshal(item.ServiceSnapshot); err == nil {
		serviceSnapshot = string(b)
	}

	result := &pb.Orders{
		Id:              item.ID,
		ConsumerId:      item.ConsumerID,
		PlayerId:        item.PlayerID,
		ServiceSnapshot: serviceSnapshot,
		Status:          item.Status,
		TotalPrice:      item.TotalPrice.String(),
		Version:         int64(item.Version),
		CreatedAt:       item.CreatedAt.Unix(),
		UpdatedAt:       item.UpdatedAt.Unix(),
	}

	if item.ShopID != nil {
		result.ShopId = item.ShopID
	}
	if item.Note != nil {
		result.Note = item.Note
	}
	if item.TimeoutJobID != nil {
		result.TimeoutJobId = item.TimeoutJobID
	}
	if item.SearchText != nil {
		result.SearchText = *item.SearchText
	}
	if item.AcceptedAt != nil {
		t := item.AcceptedAt.Unix()
		result.AcceptedAt = &t
	}
	if item.ClosedAt != nil {
		t := item.ClosedAt.Unix()
		result.ClosedAt = &t
	}
	if item.CompletedAt != nil {
		t := item.CompletedAt.Unix()
		result.CompletedAt = &t
	}
	if item.CancelledAt != nil {
		t := item.CancelledAt.Unix()
		result.CancelledAt = &t
	}

	return result
}

func toPBOrderStateLog(item *models.OrderStateLogs) *pb.OrderStateLogs {
	result := &pb.OrderStateLogs{
		Id:        item.ID,
		OrderId:   item.OrderID,
		ToStatus:  item.ToStatus,
		Action:    item.Action,
		ActorId:   item.ActorID,
		ActorRole: item.ActorRole,
		CreatedAt: item.CreatedAt.Unix(),
	}

	if item.FromStatus != nil {
		result.FromStatus = item.FromStatus
	}
	if item.Metadata != nil {
		if b, err := json.Marshal(item.Metadata); err == nil {
			metadata := string(b)
			result.Metadata = &metadata
		}
	}

	return result
}
