package routes

import (
	"bssapp-backend/auth"
	"database/sql"
	"encoding/json"
	"net/http"
)

func DebugPermissionV2(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		// sadece auth kontrolü
		claims, ok := auth.GetClaimsFromContext(r.Context())
		if !ok || claims == nil {
			http.Error(w, "unauthorized", 401)
			return
		}

		module := r.URL.Query().Get("module")
		action := r.URL.Query().Get("action")

		if module == "" || action == "" {
			http.Error(w, "module & action required", 400)
			return
		}

		rows, err := db.Query(`
			SELECT
				r.id,
				r.code,
				rp.allowed
			FROM dfrole r
			LEFT JOIN mk_sys_role_permissions rp
			  ON rp.role_id = r.id
			 AND rp.module_code = $1
			 AND rp.action = $2
			ORDER BY r.id
		`, module, action)

		if err != nil {
			http.Error(w, "db error", 500)
			return
		}
		defer rows.Close()

		type Row struct {
			RoleID  int    `json:"role_id"`
			Code    string `json:"code"`
			Allowed bool   `json:"allowed"`
		}

		var list []Row

		for rows.Next() {
			var r Row
			_ = rows.Scan(&r.RoleID, &r.Code, &r.Allowed)
			list = append(list, r)
		}

		json.NewEncoder(w).Encode(list)
	}
}
