package queries

import (
	"bssapp-backend/models"
	"database/sql"
	"fmt"
)

// GetTodayCurrencyV3 tek bir döviz türü için güncel kuru döndürür (MSSQL sürümü)
func GetTodayCurrencyV3(db *sql.DB, currencyCode string) (*models.TodayCurrencyV3, error) {
	query := `
	SELECT TOP 1 
		CurrencyCode,
		RelationCurrencyCode,
		ExchangeTypeCode,
		Rate,
		CONVERT(varchar, Date, 23) AS Date
	FROM AllExchangeRates
	WHERE CurrencyCode = @p1
	  AND RelationCurrencyCode = 'TRY'
	  AND ExchangeTypeCode = 6
	  AND Rate > 0
	ORDER BY ABS(DATEDIFF(DAY, Date, GETDATE())) ASC
	`

	row := db.QueryRow(query, currencyCode)

	var c models.TodayCurrencyV3
	err := row.Scan(&c.CurrencyCode, &c.RelationCurrencyCode, &c.ExchangeTypeCode, &c.Rate, &c.Date)
	if err != nil {
		return nil, fmt.Errorf("kur bilgisi alınamadı: %v", err)
	}

	return &c, nil
}
