package queries

import (
	"database/sql"
	"fmt"
)

// ========================================================
// 📌 GetUserList — POSTGRES FINAL (mk_dfusr)
// ========================================================
func GetUserList(db *sql.DB, search string) (*sql.Rows, error) {

	baseQuery := `
SELECT
    u.id                                AS id,               -- 1
    u.username                          AS code,             -- 2  (frontend uyumu için alias)
    u.is_active                         AS is_active,        -- 3

    -- Nebim eşleşmesi (opsiyonel)
    n.username                          AS nebim_username,   -- 4
    n.user_group_code                   AS user_group_code,  -- 5

    -- Roller
    COALESCE(string_agg(DISTINCT r.code, ', '), '')           AS role_names,        -- 6

    -- Departmanlar
    COALESCE(string_agg(DISTINCT d.title, ', '), '')          AS department_names,  -- 7

    -- Piyasalar (ÇOKLU)
    COALESCE(string_agg(DISTINCT p.title, ', '), '')          AS piyasa_names       -- 8

FROM mk_dfusr u

-- ==========================
-- 🔗 Nebim eşleşmesi
-- ==========================
LEFT JOIN dfusr_nebim_user un
  ON un.dfusr_id = u.id

LEFT JOIN mk_nebim_user n
  ON n.id = un.mk_nebim_user_id

-- ==========================
-- 🔐 Roller
-- ==========================
LEFT JOIN dfrole_usr uru
  ON uru.dfusr_id = u.id

LEFT JOIN dfrole r
  ON r.id = uru.dfrole_id

-- ==========================
-- 🏢 Departmanlar
-- ==========================
LEFT JOIN dfusr_dprt ud
  ON ud.dfusr_id = u.id

LEFT JOIN mk_dprt d
  ON d.id = ud.dprt_id

-- ==========================
-- 🌍 Piyasalar
-- ==========================
LEFT JOIN dfusr_piyasa up
  ON up.dfusr_id = u.id

LEFT JOIN mk_sales_piy p
  ON p.code = up.piyasa_code

WHERE 1 = 1
`

	// 🔍 SEARCH FILTER
	if search != "" {
		baseQuery += `
  AND (
        u.username ILIKE $1
     OR u.email ILIKE $1
     OR n.username ILIKE $1
     OR r.code ILIKE $1
     OR d.title ILIKE $1
     OR p.title ILIKE $1
  )
`
	}

	// 📌 GROUP + ORDER
	baseQuery += `
GROUP BY
    u.id,
    u.username,
    u.is_active,
    n.username,
    n.user_group_code

ORDER BY u.username
`

	// ▶ EXECUTE QUERY
	if search != "" {
		searchLike := fmt.Sprintf("%%%s%%", search)
		return db.Query(baseQuery, searchLike)
	}

	return db.Query(baseQuery)
}
