package rest

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/nexuscrm/backend/internal/application/services"
	"github.com/nexuscrm/shared/pkg/api"
	"github.com/nexuscrm/shared/pkg/constants"
)

type ConnectHandler struct {
	svcMgr *services.ServiceManager
}

func NewConnectHandler(svcMgr *services.ServiceManager) *ConnectHandler {
	return &ConnectHandler{svcMgr: svcMgr}
}

// GetNotifications handles GET /services/data/v63.0/connect/notifications
// Returns a Salesforce-compatible NotificationCollection
func (h *ConnectHandler) GetNotifications(c *gin.Context) {
	user := MustGetUser(c)

	// Query unread notifications for this user using structured criteria (parameterized)
	queryReq := api.QueryRequest{
		ObjectAPIName: constants.TableNotification,
		SelectFields:  []string{"Id", "recipient_id", "title", "body", "link", "is_read", "created_date", "notification_type"},
		Criteria: []api.QueryCriterion{
			{Field: "recipient_id", Op: "=", Val: user.ID},
			{Field: "is_read", Op: "=", Val: false},
		},
		Limit:         50,
		SortField:     "created_date",
		SortDirection: "DESC",
	}

	// Execute via QueryService
	results, err := h.svcMgr.QuerySvc.Query(c.Request.Context(), queryReq, user)
	if err != nil {
		// If table doesn't exist, generic empty response to satisfy frontend
		c.JSON(http.StatusOK, gin.H{
			"notifications": []interface{}{},
			"unreadCount":   0,
		})
		return
	}

	// 2. Map to Salesforce Connect API Structure
	// Ref: https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/connect_responses_notification_collection.htm

	notifications := make([]map[string]interface{}, 0)

	for _, row := range results.Records {
		rowMap := row

		n := map[string]interface{}{
			"id":           rowMap["Id"],
			"recipientId":  rowMap["recipient_id"],
			"type":         rowMap["notification_type"], // e.g. "TaskAssignment"
			"unread":       !getBool(rowMap["is_read"]),
			"createdDate":  rowMap["created_date"],
			"messageBody":  rowMap["body"],
			"messageTitle": rowMap["title"],
			"url":          rowMap["link"],
		}
		notifications = append(notifications, n)
	}

	response := gin.H{
		"notifications":  notifications,
		"unreadCount":    len(notifications),
		"currentPageUrl": "/services/data/v63.0/connect/notifications",
		"nextPageUrl":    nil,
	}

	c.JSON(http.StatusOK, response)
}

// RegisterRoutes registers the connect routes
func (h *ConnectHandler) RegisterRoutes(group *gin.RouterGroup) {
	group.GET("/notifications", h.GetNotifications)
}

// Helper
func getBool(v interface{}) bool {
	if b, ok := v.(bool); ok {
		return b
	}
	return false
}
