package authz

import (
	"database/sql"
	"fmt"
	"strings"
	"sync"
)

// =====================================================
// 🧠 PIYASA CACHE (USER → CODES)
// =====================================================

var (
	piyasaCache = make(map[int][]string)
	piyasaMu    sync.RWMutex
)

// =====================================================
// 📌 GET USER PIYASA CODES (CACHED)
// =====================================================

func GetUserPiyasaCodes(pg *sql.DB, userID int) ([]string, error) {

	// -----------------------------
	// CACHE READ
	// -----------------------------
	piyasaMu.RLock()
	if it, ok := piyasaCache[userID]; ok {
		piyasaMu.RUnlock()
		return it, nil
	}
	piyasaMu.RUnlock()

	// -----------------------------
	// DB QUERY
	// -----------------------------
	rows, err := pg.Query(`
		WITH user_piyasa AS (
			SELECT TRIM(up.piyasa_code) AS raw_code
			FROM dfusr_piyasa up
			WHERE up.dfusr_id = $1
			  AND up.is_allowed = true
		)
		SELECT DISTINCT
			COALESCE(p_code.code, p_title.code, u.raw_code) AS piyasa_code
		FROM user_piyasa u
		LEFT JOIN mk_sales_piy p_code
		  ON UPPER(translate(TRIM(p_code.code),  'çğıöşüÇĞİÖŞÜ', 'CGIOSUCGIOSU'))
		   = UPPER(translate(TRIM(u.raw_code),   'çğıöşüÇĞİÖŞÜ', 'CGIOSUCGIOSU'))
		LEFT JOIN mk_sales_piy p_title
		  ON UPPER(translate(TRIM(p_title.title),'çğıöşüÇĞİÖŞÜ', 'CGIOSUCGIOSU'))
		   = UPPER(translate(TRIM(u.raw_code),   'çğıöşüÇĞİÖŞÜ', 'CGIOSUCGIOSU'))
	`, userID)
	if err != nil {
		return nil, fmt.Errorf("pg piyasa query error: %w", err)
	}
	defer rows.Close()

	var out []string
	seen := make(map[string]struct{})
	for rows.Next() {
		var code string
		if err := rows.Scan(&code); err == nil {
			code = strings.ToUpper(strings.TrimSpace(code))
			if code != "" {
				if _, ok := seen[code]; ok {
					continue
				}
				seen[code] = struct{}{}
				out = append(out, code)
			}
		}
	}

	// -----------------------------
	// CACHE WRITE
	// -----------------------------
	piyasaMu.Lock()
	piyasaCache[userID] = out
	piyasaMu.Unlock()

	return out, nil
}

// =====================================================
// 🧹 CLEAR USER PIYASA CACHE
// =====================================================

func ClearPiyasaCache(userID int) {
	piyasaMu.Lock()
	defer piyasaMu.Unlock()
	delete(piyasaCache, userID)
}
