package routes

import (
	"bssapp-backend/auth"
	"bssapp-backend/ctxkeys"
	"bssapp-backend/internal/auditlog"
	"bssapp-backend/permissions"
	"bssapp-backend/repository"
	"database/sql"
	"encoding/json"
)

// auditLogFromRequest
// routes içinden çağrılır
// auditLogFromRequest
// routes içinden çağrılır
func auditLogFromRequest(
	ctx any,
	db *sql.DB,
	actionType string,
	meta map[string]any,
) {

	al := auditlog.ActivityLog{
		ActionType:     actionType,
		ActionCategory: "ADMIN",
		IsSuccess:      true,
	}

	// JWT → identity
	if c, ok := ctx.(interface {
		Value(any) any
	}); ok {
		if claims, ok := c.Value(ctxkeys.UserContextKey).(*auth.Claims); ok && claims != nil {

			// ✅ TEK KİMLİK
			al.DfUsrID = claims.ID
			al.Username = claims.Username
			al.RoleCode = claims.RoleCode

			// 🔗 MULTI ROLE → ADMIN CHECK
			roles, err := repository.GetUserRolesByUserID(db, claims.ID)
			if err == nil {
				_, isAdmin := permissions.ResolveEffectiveRoles(roles)
				if isAdmin {
					al.RoleCode = "admin"
				}
			}
		}
	}

	// meta → description
	if meta != nil {
		if b, err := json.Marshal(meta); err == nil {
			al.Description = string(b)
		}
	}

	auditlog.Write(al)
}
