package routes

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

type BrandGroupCurrencyItem struct {
	ID         int    `json:"id"`
	AnchorMode string `json:"anchor_mode"`
}

type BrandGroupCurrencyPayload struct {
	Items []BrandGroupCurrencyItem `json:"items"`
}

func GetBrandGroupCurrencyHandler(pg *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		if err := queries.EnsureBrandClassificationTables(pg); err != nil {
			http.Error(w, "brand tables bootstrap error", http.StatusInternalServerError)
			return
		}

		traceID := utils.TraceIDFromRequest(r)
		ctx := utils.ContextWithTraceID(r.Context(), traceID)

		rows, err := queries.ListBrandGroups(ctx, pg)
		if err != nil {
			http.Error(w, "brand group currency list error", http.StatusInternalServerError)
			return
		}
		_ = json.NewEncoder(w).Encode(rows)
	}
}

func SaveBrandGroupCurrencyHandler(pg *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		if err := queries.EnsureBrandClassificationTables(pg); err != nil {
			http.Error(w, "brand tables bootstrap error", http.StatusInternalServerError)
			return
		}

		var payload BrandGroupCurrencyPayload
		if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
			http.Error(w, "invalid payload", http.StatusBadRequest)
			return
		}
		if len(payload.Items) == 0 {
			_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "updated": 0})
			return
		}

		traceID := utils.TraceIDFromRequest(r)
		ctx := utils.ContextWithTraceID(r.Context(), traceID)

		tx, err := pg.BeginTx(ctx, nil)
		if err != nil {
			http.Error(w, "pg transaction start error", http.StatusInternalServerError)
			return
		}
		defer tx.Rollback()

		updated := 0
		for _, item := range payload.Items {
			if item.ID <= 0 {
				http.Error(w, "invalid id", http.StatusBadRequest)
				return
			}
			mode := strings.ToUpper(strings.TrimSpace(item.AnchorMode))
			if mode != "TRY" && mode != "USD" {
				http.Error(w, "invalid anchor_mode", http.StatusBadRequest)
				return
			}
			if err := queries.SetBrandGroupAnchorMode(ctx, tx, item.ID, mode); err != nil {
				http.Error(w, "brand group currency save error", http.StatusInternalServerError)
				return
			}
			if err := queries.SyncPricingRuleAnchorModesByGroup(ctx, tx, item.ID, mode); err != nil {
				http.Error(w, "pricing rule anchor sync error", http.StatusInternalServerError)
				return
			}
			updated++
		}

		if err := tx.Commit(); err != nil {
			http.Error(w, "pg transaction commit error", http.StatusInternalServerError)
			return
		}
		_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "updated": updated})
	}
}
