package integration_test

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

func TestDistributionArtifactsExistAndReferenceRequiredEnv(t *testing.T) {
	root := repoRoot(t)
	for _, path := range []string{
		filepath.Join(root, "Dockerfile"),
		filepath.Join(root, ".env.example"),
		filepath.Join(root, "docker-compose.yml"),
		filepath.Join(root, "docs", "DEPLOYMENT.md"),
	} {
		if _, err := os.Stat(path); err != nil {
			t.Fatalf("required distribution artifact %q missing: %v", path, err)
		}
	}

	dockerfile := mustReadText(t, filepath.Join(root, "Dockerfile"))
	if !strings.Contains(dockerfile, "SUB2API_CRM_ADMIN_TOKEN") {
		t.Fatalf("Dockerfile must document runtime dependency on SUB2API_CRM_ADMIN_TOKEN; content=%s", dockerfile)
	}

	envExample := mustReadText(t, filepath.Join(root, ".env.example"))
	for _, key := range []string{"SUB2API_CRM_LISTEN_ADDR", "SUB2API_CRM_SQLITE_DSN", "SUB2API_CRM_ADMIN_TOKEN"} {
		if !strings.Contains(envExample, key+"=") {
			t.Fatalf(".env.example missing %s; content=%s", key, envExample)
		}
	}

	compose := mustReadText(t, filepath.Join(root, "docker-compose.yml"))
	if !strings.Contains(compose, "/healthz") {
		t.Fatalf("docker-compose.yml missing healthz probe; content=%s", compose)
	}

	deployment := mustReadText(t, filepath.Join(root, "docs", "DEPLOYMENT.md"))
	for _, needle := range []string{"docker compose up --build -d", "SUB2API_CRM_ADMIN_TOKEN", "/healthz"} {
		if !strings.Contains(deployment, needle) {
			t.Fatalf("DEPLOYMENT.md missing %q; content=%s", needle, deployment)
		}
	}
}

func repoRoot(t *testing.T) string {
	t.Helper()
	root, err := filepath.Abs(filepath.Join("..", ".."))
	if err != nil {
		t.Fatalf("resolve repo root: %v", err)
	}
	return root
}

func mustReadText(t *testing.T, path string) string {
	t.Helper()
	content, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read %s: %v", path, err)
	}
	return string(content)
}
