package dialectsfcrm

import (
	"context"
	"fmt"
	"net/http"

	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/dialect"
	"github.com/nexuscrm/shared/pkg/queryspec"
)

// ConnectNotificationsNeutralHandler handles GET /connect/notifications.
func ConnectNotificationsNeutralHandler(ctx context.Context, req *dialect.Request, deps dialect.Deps) (*dialect.Response, error) {
	query := deps.Contracts.Query
	if query == nil {
		return &dialect.Response{
			Status: http.StatusOK,
			Body: map[string]any{
				"notifications": []any{},
				"unreadCount":   0,
			},
		}, nil
	}

	queryReq := queryspec.QuerySpec{
		ObjectAPIName: constants.TableNotification,
		SelectFields:  []string{"Id", "recipient_id", "title", "body", "link", "is_read", constants.FieldNotification_CreatedDate, "notification_type"},
		Filter: queryspec.CriteriaPredicate([]queryspec.QueryCriterion{
			{Field: "recipient_id", Op: "=", Val: req.User.ID},
			{Field: "is_read", Op: "=", Val: false},
		}),
		Limit:         50,
		SortField:     constants.FieldNotification_CreatedDate,
		SortDirection: "DESC",
	}

	results, err := query.Query(ctx, queryReq, req.User)
	if err != nil {
		return &dialect.Response{
			Status: http.StatusOK,
			Body: map[string]any{
				"notifications": []any{},
				"unreadCount":   0,
			},
		}, nil
	}

	notifications := make([]map[string]any, 0)
	for _, row := range results.Records {
		n := map[string]any{
			"id":           row["Id"],
			"recipientId":  row["recipient_id"],
			"type":         row["notification_type"],
			"unread":       !connectBool(row["is_read"]),
			"createdDate":  row[constants.FieldNotification_CreatedDate],
			"messageBody":  row["body"],
			"messageTitle": row["title"],
			"url":          row["link"],
		}
		notifications = append(notifications, n)
	}

	version := apiVersionOrDefault(req.Version)
	return &dialect.Response{
		Status: http.StatusOK,
		Body: map[string]any{
			"notifications":  notifications,
			"unreadCount":    len(notifications),
			"currentPageUrl": fmt.Sprintf("/services/data/%s/connect/notifications", version),
			"nextPageUrl":    nil,
		},
	}, nil
}

func connectBool(v any) bool {
	b, ok := v.(bool)
	return ok && b
}
