package paymentsub

import (
	"github.com/pingcap/dbaas/billing2/db"
	"github.com/pingcap/dbaas/billing2/db/entity"
	"github.com/pingcap/dbaas/billing2/forms"
)

type FXRateModel struct{}

func getInvoiceAppliedFXRateFromEntity(ent *entity.InvoiceAppliedFX) *forms.InvoiceAppliedFXRate {
	return &forms.InvoiceAppliedFXRate{
		ID:     ent.ID,
		Date:   ent.Date,
		Base:   forms.Currency(ent.Base),
		Target: forms.Currency(ent.Target),
		Value:  ent.Value,
	}
}

func (i *FXRateModel) GetInvoiceAppliedFX(base, target forms.Currency) (*forms.InvoiceAppliedFXRate, error) {
	var ent entity.InvoiceAppliedFX
	err := entity.NewInvoiceAppliedFXQuerySet(db.GetDB()).BaseEq(string(base)).TargetEq(string(target)).OrderDescByDate().OrderDescByCreatedAt().One(&ent)
	if err != nil {
		return nil, err
	}
	return getInvoiceAppliedFXRateFromEntity(&ent), nil
}

func (i *FXRateModel) CreateInvoiceAppliedFX(in *forms.InvoiceAppliedFXRate) (*forms.InvoiceAppliedFXRate, error) {
	ent := entity.InvoiceAppliedFX{
		Date:   in.Date,
		Base:   string(in.Base),
		Target: string(in.Target),
		Value:  in.Value,
	}
	err := ent.Create(db.GetDB())
	if err != nil {
		return nil, err
	}
	return getInvoiceAppliedFXRateFromEntity(&ent), nil
}
