package routes

import (
	"bssapp-backend/models"
	"bssapp-backend/queries"
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
)

// ✅ Model + pb/currency paramına göre fiyat döner (debug log’lu)
func GetOrderPriceListB2BHandler(pg *sql.DB, mssql *sql.DB) http.HandlerFunc {

	return func(w http.ResponseWriter, r *http.Request) {

		model := r.URL.Query().Get("model")
		if model == "" {
			model = r.URL.Query().Get("code")
		}

		cur := r.URL.Query().Get("currency")
		if cur == "" {
			cur = r.URL.Query().Get("pb")
		}

		if model == "" || cur == "" {
			http.Error(w, "Eksik parametre", 400)
			return
		}

		cur = strings.ToUpper(cur)

		fmt.Printf("💰 [MINPRICE] model=%s cur=%s\n", model, cur)

		var (
			price float64
			rate  float64 = 1
		)

		/* ======================
		   USD / EUR → Direkt
		====================== */

		if cur == "USD" || cur == "EUR" {

			p, err := queries.GetOrderPriceListB2B(pg, model, cur)

			if err != nil {
				http.Error(w, cur+" fiyat bulunamadı", 404)
				return
			}

			price = p.Price

		} else if cur == "TRY" {

			/* ======================
			   TRY → USD * Kur
			====================== */

			// 1️⃣ USD fiyat
			p, err := queries.GetOrderPriceListB2B(pg, model, "USD")
			if err != nil {
				http.Error(w, "USD fiyat bulunamadı", 404)
				return
			}

			// 2️⃣ USD→TRY satış
			r, err := queries.GetCachedCurrencyV3(mssql, "USD")

			if err != nil {
				http.Error(w, "USD kuru bulunamadı", 503)
				return
			}

			rate = r.Rate
			price = p.Price * rate

		} else if cur == "GBP" {

			/* ======================
			   GBP → USD Bridge
			====================== */

			// 1️⃣ USD fiyat
			p, err := queries.GetOrderPriceListB2B(pg, model, "USD")
			if err != nil {
				http.Error(w, "USD fiyat bulunamadı", 404)
				return
			}

			// 2️⃣ USD→TRY
			usd, err := queries.GetCachedCurrencyV3(mssql, "USD")

			if err != nil {
				http.Error(w, "USD kuru yok", 503)
				return
			}

			// 3️⃣ GBP→TRY
			gbp, err := queries.GetCachedCurrencyV3(mssql, "GBP")
			if err != nil {
				http.Error(w, "GBP kuru yok", 503)
				return
			}

			rate = usd.Rate / gbp.Rate
			price = p.Price * rate

		} else {

			http.Error(w, "Desteklenmeyen para birimi", 400)
			return
		}

		resp := models.OrderPriceListB2B{
			ModelCode:    model,
			CurrencyCode: cur,
			Price:        price,
			RateToTRY:    rate,
			PriceTRY:     price,
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(resp)

		fmt.Printf("✅ [MINPRICE] %s → %.2f %s\n", model, price, cur)
	}
}
