package main

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

func TestGenerateStylesConcatenatesSourcesInOrder(t *testing.T) {
	root := t.TempDir()
	uiDir := filepath.Join(root, "internal", "web", "ui")
	catalogDir := filepath.Join(uiDir, "catalog")
	if err := os.MkdirAll(catalogDir, 0o755); err != nil {
		t.Fatalf("mkdir css dirs: %v", err)
	}

	sources := map[string]string{
		filepath.Join(uiDir, "base.css"):         "/* base */\n.base { color: red; }\n",
		filepath.Join(catalogDir, "catalog.css"): "/* catalog */\n.catalog-page { color: green; }\n",
		filepath.Join(uiDir, "button.css"):       "/* button */\n.ui-button { color: blue; }\n",
	}
	for path, body := range sources {
		if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
			t.Fatalf("write %s: %v", path, err)
		}
	}

	outputPath := filepath.Join(root, "static", "styles.css")
	sourcePaths := []string{
		filepath.Join(uiDir, "base.css"),
		filepath.Join(catalogDir, "catalog.css"),
		filepath.Join(uiDir, "button.css"),
	}
	if err := generateStyles(sourcePaths, outputPath); err != nil {
		t.Fatalf("generate styles: %v", err)
	}

	content, err := os.ReadFile(outputPath)
	if err != nil {
		t.Fatalf("read output: %v", err)
	}

	got := string(content)
	for _, want := range []string{
		"/* base */",
		".base { color: red; }",
		"/* catalog */",
		".catalog-page { color: green; }",
		"/* button */",
		".ui-button { color: blue; }",
	} {
		if !strings.Contains(got, want) {
			t.Fatalf("expected %q in %q", want, got)
		}
	}
	if strings.Index(got, "/* base */") > strings.Index(got, "/* catalog */") {
		t.Fatalf("expected base.css before catalog.css, got %q", got)
	}
	if strings.Index(got, "/* catalog */") > strings.Index(got, "/* button */") {
		t.Fatalf("expected catalog.css before button.css, got %q", got)
	}
}
