package service

import (
	"context"
	"encoding/json"
	"os"
	"path/filepath"
	"testing"

	"wucher/internal/queue"
)

func TestMockEmailSenderSend(t *testing.T) {
	dir := t.TempDir()
	sender := NewMockEmailSender(dir)

	result, err := sender.Send(context.Background(), queue.EmailJob{
		JobID:       "job-123",
		MessageType: "password_reset",
		To:          "user@example.com",
		Subject:     "Reset password",
		TextBody:    "plain body",
		HTMLBody:    "<p>html body</p>",
		Tags: map[string]string{
			"message_type": "password_reset",
		},
	})
	if err != nil {
		t.Fatalf("send: %v", err)
	}
	if result.Provider != "mock" || result.ProviderMessageID == "" || result.RequestID == "" {
		t.Fatalf("unexpected result: %+v", result)
	}

	entries, err := os.ReadDir(dir)
	if err != nil {
		t.Fatalf("read dir: %v", err)
	}
	if len(entries) != 1 {
		t.Fatalf("expected one stored email, got %d", len(entries))
	}
	data, err := os.ReadFile(filepath.Join(dir, entries[0].Name()))
	if err != nil {
		t.Fatalf("read file: %v", err)
	}
	var record MockEmailRecord
	if err := json.Unmarshal(data, &record); err != nil {
		t.Fatalf("unmarshal record: %v", err)
	}
	if record.JobID != "job-123" || record.MessageType != "password_reset" || record.To != "user@example.com" {
		t.Fatalf("unexpected record: %+v", record)
	}
	if record.TextBody != "plain body" || record.HTMLBody != "<p>html body</p>" {
		t.Fatalf("unexpected bodies: %+v", record)
	}
}

func TestMockEmailSenderValidation(t *testing.T) {
	if _, err := NewMockEmailSender("").Send(context.Background(), queue.EmailJob{
		To:       "user@example.com",
		Subject:  "Hello",
		TextBody: "World",
	}); err == nil {
		t.Fatalf("expected config error")
	}
}
