package templates

import (
	"context"
	"encoding/json"
	"testing"
)

func TestDefinitions(t *testing.T) {
	svc := NewService(nil)
	defs := svc.ListDefinitions()
	if len(defs) == 0 {
		t.Fatal("expected at least 1 report definition")
	}

	invDef, err := svc.GetDefinition("invoice-print")
	if err != nil {
		t.Fatalf("failed to get invoice-print definition: %v", err)
	}
	if invDef.Code != "invoice-print" {
		t.Errorf("expected invoice-print, got %s", invDef.Code)
	}
	if len(invDef.Parameters) == 0 {
		t.Error("expected parameters for invoice-print")
	}
	if len(invDef.SampleData) == 0 {
		t.Error("expected sample data for invoice-print")
	}

	_, err = svc.GetDefinition("unknown-report")
	if err == nil {
		t.Error("expected error for unknown report code")
	}
}

func TestCreateTemplateValidation(t *testing.T) {
	svc := NewService(nil)
	ctx := context.Background()

	// Empty report code
	_, err := svc.CreateTemplate(ctx, CreateTemplateInput{}, nil)
	if err == nil {
		t.Error("expected error for empty report code")
	}

	// Empty template data
	_, err = svc.CreateTemplate(ctx, CreateTemplateInput{
		ReportCode: "invoice-print",
	}, nil)
	if err == nil {
		t.Error("expected error for empty template data")
	}

	// Unknown report code
	_, err = svc.CreateTemplate(ctx, CreateTemplateInput{
		ReportCode:   "nonexistent-code",
		TemplateData: []byte(`{}`),
	}, nil)
	if err == nil {
		t.Error("expected error for unregistered report code")
	}
}

func TestListTemplates_EmptyReturnsSliceNotNil(t *testing.T) {
	svc := NewService(nil)
	ctx := context.Background()

	items, err := svc.ListTemplates(ctx, "", "draft")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if items == nil {
		t.Fatal("expected empty slice, got nil")
	}
	if len(items) != 0 {
		t.Fatalf("expected 0 items, got %d", len(items))
	}

	raw, err := json.Marshal(items)
	if err != nil {
		t.Fatalf("json marshal error: %v", err)
	}
	if string(raw) != "[]" {
		t.Fatalf("expected JSON '[]', got '%s'", string(raw))
	}
}
