package mongo

import (
	"fmt"
	"reflect"

	"github.com/shopspring/decimal"
	"go.mongodb.org/mongo-driver/v2/bson"
)

type MgoDecimal struct{}

var (
	_ bson.ValueEncoder = &MgoDecimal{}
	_ bson.ValueDecoder = &MgoDecimal{}
)

func (dc *MgoDecimal) EncodeValue(_ bson.EncodeContext, w bson.ValueWriter, value reflect.Value) error {
	// TODO 待確認是否有非decimal.Decimal type而導致error的場景
	dec, ok := value.Interface().(decimal.Decimal)
	if !ok {
		return fmt.Errorf("value %v to encode is not of type decimal.Decimal", value)
	}

	// Convert decimal.Decimal to bson.Decimal128.
	primDec, err := bson.ParseDecimal128(dec.String())
	if err != nil {
		return fmt.Errorf("converting decimal.Decimal %v to bson.Decimal128 error: %w", dec, err)
	}

	return w.WriteDecimal128(primDec)
}

func (dc *MgoDecimal) DecodeValue(_ bson.DecodeContext, r bson.ValueReader, value reflect.Value) error {
	primDec, err := r.ReadDecimal128()
	if err != nil {
		return fmt.Errorf("reading bson.Decimal128 from ValueReader error: %w", err)
	}

	// Convert bson.Decimal128 to decimal.Decimal.
	dec, err := decimal.NewFromString(primDec.String())
	if err != nil {
		return fmt.Errorf("converting bson.Decimal128 %v to decimal.Decimal error: %w", primDec, err)
	}

	// set as decimal.Decimal type
	value.Set(reflect.ValueOf(dec))

	return nil
}
