package service

import (
	"context"
	"errors"
	"testing"

	"wucher/internal/queue"
)

type emailSenderStub struct {
	sendFn func(ctx context.Context, job EmailJob) (EmailDeliveryResult, error)
}

func (s emailSenderStub) Send(ctx context.Context, job EmailJob) (EmailDeliveryResult, error) {
	if s.sendFn != nil {
		return s.sendFn(ctx, job)
	}
	return EmailDeliveryResult{}, nil
}

func TestEmailDeliveryHandler_Handle_SkipSend(t *testing.T) {
	called := false
	handler := NewEmailDeliveryHandler(emailSenderStub{
		sendFn: func(context.Context, EmailJob) (EmailDeliveryResult, error) {
			called = true
			return EmailDeliveryResult{}, nil
		},
	}, nil)

	err := handler.Handle(context.Background(), &queue.Envelope{
		MessageID: "msg-1",
		Payload: EmailJob{
			To:       "user@example.com",
			Subject:  "Verify",
			TextBody: "Body",
			Metadata: map[string]string{
				"skip_send": "true",
			},
		},
	})
	if err != nil {
		t.Fatalf("expected nil error, got %v", err)
	}
	if called {
		t.Fatalf("expected sender not called when skip_send=true")
	}
}

func TestEmailDeliveryHandler_Handle_SendWhenNotSkipped(t *testing.T) {
	called := false
	handler := NewEmailDeliveryHandler(emailSenderStub{
		sendFn: func(context.Context, EmailJob) (EmailDeliveryResult, error) {
			called = true
			return EmailDeliveryResult{}, nil
		},
	}, nil)

	err := handler.Handle(context.Background(), &queue.Envelope{
		MessageID: "msg-2",
		Payload: EmailJob{
			To:       "user@example.com",
			Subject:  "Verify",
			TextBody: "Body",
		},
	})
	if err != nil {
		t.Fatalf("expected nil error, got %v", err)
	}
	if !called {
		t.Fatalf("expected sender called when skip_send is absent")
	}
}

func TestEmailDeliveryHandler_Handle_ClassifyErrorWhenNotSkipped(t *testing.T) {
	handler := NewEmailDeliveryHandler(emailSenderStub{
		sendFn: func(context.Context, EmailJob) (EmailDeliveryResult, error) {
			return EmailDeliveryResult{}, errors.New("network timeout")
		},
	}, nil)

	err := handler.Handle(context.Background(), &queue.Envelope{
		MessageID: "msg-3",
		Payload: EmailJob{
			To:       "user@example.com",
			Subject:  "Verify",
			TextBody: "Body",
		},
	})
	if err == nil {
		t.Fatalf("expected classified error")
	}
}
