package importer

import (
	"context"
	"strings"
	"testing"

	"github.com/unkn0wn-root/resterm/internal/restfile"
)

type stubWriter struct {
	doc  *restfile.Document
	dst  string
	opts WriterOptions
}

func (w *stubWriter) WriteDocument(
	_ context.Context,
	doc *restfile.Document,
	dst string,
	opts WriterOptions,
) error {
	w.doc = doc
	w.dst = dst
	w.opts = opts
	return nil
}

func TestGenerateHTTPFile(t *testing.T) {
	w := &stubWriter{}
	svc := Service{Writer: w}
	cmd := "curl https://example.com --silent"
	opts := WriterOptions{
		HeaderComment:     "Generated by tests",
		OverwriteExisting: true,
	}

	if err := svc.GenerateHTTPFile(context.Background(), cmd, "out.http", opts); err != nil {
		t.Fatalf("generate http file: %v", err)
	}

	if w.doc == nil || len(w.doc.Requests) != 1 {
		t.Fatalf("expected 1 request, got %v", w.doc)
	}
	if w.dst != "out.http" {
		t.Fatalf("unexpected destination %q", w.dst)
	}
	if !strings.Contains(w.opts.HeaderComment, "Generated by tests") {
		t.Fatalf("missing base header comment: %q", w.opts.HeaderComment)
	}
	if !strings.Contains(w.opts.HeaderComment, "Source:") {
		t.Fatalf("missing source header: %q", w.opts.HeaderComment)
	}
	if !strings.Contains(w.opts.HeaderComment, "curl https://example.com") {
		t.Fatalf("missing command in header: %q", w.opts.HeaderComment)
	}
	if !strings.Contains(w.opts.HeaderComment, "Warning: unsupported flag --silent") {
		t.Fatalf("missing warning in header: %q", w.opts.HeaderComment)
	}
}

func TestBuildDocMulti(t *testing.T) {
	cmd := "curl https://a.test\n\ncurl https://b.test --silent"
	doc, warn, err := buildDoc(cmd)
	if err != nil {
		t.Fatalf("build doc: %v", err)
	}
	if len(doc.Requests) != 2 {
		t.Fatalf("expected 2 requests, got %d", len(doc.Requests))
	}
	if len(warn) == 0 {
		t.Fatalf("expected warnings")
	}
}
