package writer

import (
	"context"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/unkn0wn-root/resterm/internal/openapi"
	"github.com/unkn0wn-root/resterm/internal/openapi/generator"
	"github.com/unkn0wn-root/resterm/internal/openapi/parser"
)

func TestFileWriter(t *testing.T) {
	t.Parallel()

	loader := parser.NewLoader()
	specPath := filepath.Join("..", "testdata", "deviceinventory.yaml")
	spec, err := loader.Parse(context.Background(), specPath, openapi.ParseOptions{})
	if err != nil {
		t.Fatalf("parse spec: %v", err)
	}

	gen := generator.NewBuilder()
	doc, err := gen.Generate(context.Background(), spec, openapi.GeneratorOptions{})
	if err != nil {
		t.Fatalf("generate: %v", err)
	}

	dest := filepath.Join(t.TempDir(), "deviceinventory.http")
	fw := NewFileWriter()
	opts := openapi.WriterOptions{
		HeaderComment:     "Generated by resterm tests",
		OverwriteExisting: false,
	}
	if err := fw.WriteDocument(context.Background(), doc, dest, opts); err != nil {
		t.Fatalf("write document: %v", err)
	}

	got, err := os.ReadFile(dest)
	if err != nil {
		t.Fatalf("read generated file: %v", err)
	}

	wantPath := filepath.Join("testdata", "deviceinventory.http")
	want, err := os.ReadFile(wantPath)
	if err != nil {
		t.Fatalf("read golden file: %v", err)
	}

	if strings.TrimSpace(string(got)) != strings.TrimSpace(string(want)) {
		t.Fatalf(
			"generated content does not match golden.\nGot:\n%s\nWant:\n%s",
			string(got),
			string(want),
		)
	}

	if err := fw.WriteDocument(context.Background(), doc, dest, opts); err == nil {
		t.Fatalf("expected overwrite prevention error")
	}
}
