package feed

import (
	"context"
	"fmt"
	"log/slog"
)

type Handler struct {
	Service *Service
	logger  *slog.Logger
}

func NewFeedHandler(logger *slog.Logger, service *Service) *Handler {
	return &Handler{
		Service: service,
		logger:  logger,
	}
}

func (h *Handler) CreateEvent(ctx context.Context, event *Event) error {
	if event == nil {
		h.logger.Error("CreateEvent: empty event",
			slog.String("error", ErrCreationInvalidData.Error()))

		return ErrCreationInvalidData
	}

	h.logger.Debug("CreateEvent: Attempting to create event",
		slog.String("type", event.EventType.String()),
		slog.String("ownerID", event.OwnerId))

	if event.OwnerId == "" || event.EventType == "" || event.Message == "" {
		h.logger.Error("CreateEvent: Validation error",
			slog.String("error", ErrCreationInvalidData.Error()),
			slog.String("type", event.EventType.String()),
			slog.String("ownerID", event.OwnerId),
			slog.String("message", event.Message),
		)

		return ErrCreationInvalidData
	}

	if err := h.Service.AddUserEvent(ctx, event); err != nil {
		h.logger.Error("CreateEvent: Service error",
			slog.String("error", err.Error()),
			slog.String("type", event.EventType.String()),
			slog.String("ownerID", event.OwnerId))

		return fmt.Errorf("Error creating event: %w", err)
	}

	h.logger.Debug("CreateEvent: Successfully created event",
		slog.String("eventID", event.Id),
		slog.String("type", event.EventType.String()),
		slog.String("ownerID", event.OwnerId))

	return nil
}

func (h *Handler) CancelEvent(ctx context.Context, attachmentId string, reason string) error {
	h.logger.Debug("CancelEvent: Attempting to cancel event",
		slog.String("attachmentID", attachmentId),
	)

	if attachmentId == "" {
		h.logger.Error("CancelEvent: Validation error",
			slog.String("error", "attachment Id is required"))

		return ErrAttachmentIDRequired
	}

	if reason == "" {
		h.logger.Error("CancelEvent: Validation error",
			slog.String("error", "cancellation reason is required"),
			slog.String("attachmentID", attachmentId))

		return ErrCancellationReasonRequired
	}

	if err := h.Service.CancelEvents(ctx, attachmentId, reason); err != nil {
		h.logger.Error("CancelEvent: Service error",
			slog.String("error", err.Error()),
			slog.String("attachmentID", attachmentId))

		return fmt.Errorf("error cancelling event: %w", err)
	}

	h.logger.Debug("CancelEvent: Successfully cancelled event",
		slog.String("attachmentID", attachmentId))

	return nil
}

func (h *Handler) GetCompanyIdByUidTmp(ctx context.Context, ownerID string) ([]string, error) {
	return h.Service.GetCompanyIdsByUid(ctx, ownerID)
}

func (h *Handler) GetAgentIdBySubmissionId(ctx context.Context, submissionId string) (string, error) {
	return h.Service.GetAgentIdBySubmissionId(ctx, submissionId)
}
