// Copyright AGNTCY Contributors (https://github.com/agntcy)
// SPDX-License-Identifier: Apache-2.0

package client

import (
	"context"
	"errors"
	"fmt"
	"io"

	routingv1 "github.com/agntcy/dir/api/routing/v1"
	"github.com/agntcy/dir/utils/logging"
)

var logger = logging.Logger("client")

func (c *Client) Publish(ctx context.Context, req *routingv1.PublishRequest) error {
	_, err := c.RoutingServiceClient.Publish(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to publish object: %w", err)
	}

	return nil
}

func (c *Client) List(ctx context.Context, req *routingv1.ListRequest) (<-chan *routingv1.ListResponse, error) {
	stream, err := c.RoutingServiceClient.List(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("failed to create list stream: %w", err)
	}

	resCh := make(chan *routingv1.ListResponse, 100) //nolint:mnd

	go func() {
		defer close(resCh)

		for {
			obj, err := stream.Recv()
			if errors.Is(err, io.EOF) {
				break
			}

			if err != nil {
				logger.Error("error receiving object", "error", err)

				return
			}

			// Stream ListResponse directly (no legacy wrapper)
			resCh <- obj
		}
	}()

	return resCh, nil
}

func (c *Client) SearchRouting(ctx context.Context, req *routingv1.SearchRequest) (<-chan *routingv1.SearchResponse, error) {
	stream, err := c.RoutingServiceClient.Search(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("failed to create search stream: %w", err)
	}

	resCh := make(chan *routingv1.SearchResponse, 100) //nolint:mnd

	go func() {
		defer close(resCh)

		for {
			obj, err := stream.Recv()
			if errors.Is(err, io.EOF) {
				break
			}

			if err != nil {
				logger.Error("error receiving search result", "error", err)

				return
			}

			// Stream SearchResponse directly
			resCh <- obj
		}
	}()

	return resCh, nil
}

func (c *Client) Unpublish(ctx context.Context, req *routingv1.UnpublishRequest) error {
	_, err := c.RoutingServiceClient.Unpublish(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to unpublish object: %w", err)
	}

	return nil
}
