package queries

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

// GetOrderPriceListB2B → model + currency bazlı ürün fiyatını döndürür (PostgreSQL sürümü)
func GetOrderPriceListB2B(db *sql.DB, modelCode string, currency string) (*models.OrderPriceListB2B, error) {
	query := `
	SELECT 
		mmitem.code AS ModelCode,
		sdprc.crn AS CurrencyCode,
		sdprc.prc AS Price,
		sdprc.sdprcgrp_id AS PriceGroupID,
		TO_CHAR(sdprc.zlins_dttm, 'YYYY-MM-DD') AS LastUpdate
	FROM sdprc
	LEFT JOIN mmitem ON sdprc.mmitem_id = mmitem.id
	WHERE mmitem.code = $1
	  AND sdprc.prc IS NOT NULL
	  AND sdprc.prc > 0
	  AND sdprc.crn = $2
	  AND sdprc.sdprcgrp_id = 1
	ORDER BY sdprc.zlins_dttm DESC
	LIMIT 1;
	`

	row := db.QueryRow(query, modelCode, currency)
	var p models.OrderPriceListB2B
	err := row.Scan(&p.ModelCode, &p.CurrencyCode, &p.Price, &p.PriceGroupID, &p.LastUpdate)
	if err != nil {
		return nil, fmt.Errorf("ürün fiyatı bulunamadı: %v", err)
	}
	return &p, nil
}
