package usecase

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

func TestPlaywrightBrowsersPathExtractsBundledBrowser(t *testing.T) {
	tmp := t.TempDir()
	scriptDir := filepath.Join(tmp, "scripts")
	sourceDir := filepath.Join(tmp, "source")
	browser := filepath.Join(sourceDir, "chromium_headless_shell-1193", "chrome-headless-shell")
	if err := os.MkdirAll(filepath.Dir(browser), 0o750); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(browser, []byte("browser"), 0o750); err != nil {
		t.Fatal(err)
	}
	if err := os.MkdirAll(scriptDir, 0o750); err != nil {
		t.Fatal(err)
	}
	archive := filepath.Join(scriptDir, "playwright-browsers.tar.gz")
	if output, err := exec.Command("tar", "-czf", archive, "-C", sourceDir, ".").CombinedOutput(); err != nil {
		t.Fatalf("create browser archive: %v: %s", err, output)
	}
	t.Setenv("PLAYWRIGHT_RUNTIME_BROWSERS_PATH", filepath.Join(tmp, "runtime"))

	got, err := playwrightBrowsersPath(filepath.Join(scriptDir, "scrape.mjs"))
	if err != nil {
		t.Fatal(err)
	}
	info, err := os.Stat(filepath.Join(got, "chromium_headless_shell-1193", "chrome-headless-shell"))
	if err != nil {
		t.Fatal(err)
	}
	if info.Mode()&0o111 == 0 {
		t.Fatalf("browser is not executable: mode %s", info.Mode())
	}
}
