package routes

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

/* =====================================================
   HANDLER
===================================================== */

type PermissionHandler struct {
	DB   *sql.DB
	Repo *permissions.PermissionRepository
}

func NewPermissionHandler(db *sql.DB) *PermissionHandler {
	return &PermissionHandler{
		DB:   db,
		Repo: permissions.NewPermissionRepository(db),
	}
}

/* =====================================================
   POST /api/permissions/matrix
===================================================== */

func (h *PermissionHandler) UpdatePermissionMatrix(
	w http.ResponseWriter,
	r *http.Request,
) {

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

	var req []permissions.PermissionUpdateRequest

	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "invalid payload", 400)
		return
	}

	if len(req) == 0 {
		w.WriteHeader(http.StatusOK)
		return
	}

	err := h.Repo.UpdatePermissions(req)
	if err != nil {
		http.Error(w, "db error", 500)
		return
	}

	json.NewEncoder(w).Encode(map[string]any{
		"success": true,
	})
}
func GetMyPermissionMatrix(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		w.Header().Set("Content-Type", "application/json; charset=utf-8")

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

		var roleID int

		err := db.QueryRow(`
			SELECT id FROM dfrole WHERE LOWER(code)=LOWER($1)
		`, claims.RoleCode).Scan(&roleID)

		if err != nil {
			http.Error(w, "role resolve error", 500)
			return
		}

		repo := permissions.NewPermissionRepository(db)

		raw, err := repo.GetPermissionMatrixForRoles([]int{roleID})
		if err != nil {
			http.Error(w, "db error", 500)
			return
		}

		// 🔥 FRONTEND FORMAT
		type Row struct {
			Module  string `json:"module"`
			Action  string `json:"action"`
			Allowed bool   `json:"allowed"`
		}

		list := make([]Row, 0, len(raw))

		for _, p := range raw {

			list = append(list, Row{
				Module:  p.ModuleCode, // 👈 burası önemli
				Action:  p.Action,
				Allowed: p.Allowed,
			})
		}

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