package currencyRepo

import (
	"git.ma-al.com/goc_daniel/b2b/app/db"
	"git.ma-al.com/goc_daniel/b2b/app/model"
	"git.ma-al.com/goc_daniel/b2b/app/utils/query/filters"
	"git.ma-al.com/goc_daniel/b2b/app/utils/query/find"
)

type UICurrencyRepo interface {
	CreateConversionRate(currencyRate *model.CurrencyRate) error
	Get(id uint) (*model.Currency, error)
}

type CurrencyRepo struct{}

func New() UICurrencyRepo {
	return &CurrencyRepo{}
}

func (repo *CurrencyRepo) CreateConversionRate(currencyRate *model.CurrencyRate) error {
	return db.DB.Create(currencyRate).Error
}

func (repo *CurrencyRepo) Get(id uint) (*model.Currency, error) {
	var currency model.Currency

	err := db.DB.Table("b2b_currencies c").
		Select("c.*, r.conversion_rate").
		Joins(`
		LEFT JOIN b2b_currency_rates r 
		ON r.b2b_id_currency = c.id 
		AND r.created_at = (
			SELECT MAX(created_at) 
			FROM b2b_currency_rates 
			WHERE b2b_id_currency = c.id
		)
	`).
		Where("c.id = ?", id).
		Scan(&currency).Error

	return &currency, err
}

func (repo *CurrencyRepo) Find(langId uint, p find.Paging, filt *filters.FiltersList) (*find.Found[model.Currency], error) {

	found, err := find.Paginate[model.Currency](langId, p, db.DB.
		Model(&model.Currency{}).
		Scopes(filt.All()...),
	)

	return &found, err
}
