package webtest
import (
"context"
"database/sql"
"io"
"log/slog"
"strings"
"sync"
"testing"
"time"
"amadan.net/rastrillo/rastrillo/crypto"
"amadan.net/oficina/base/internal/config"
"amadan.net/oficina/base/internal/install"
"amadan.net/oficina/base/internal/platform"
"amadan.net/oficina/base/internal/store"
"amadan.net/oficina/base/internal/web"
)
// recorder is a fake Installer that records its calls.
type recorder struct {
mu sync.Mutex
installs []string
uninstalls []string
uninstallErr error
}
func newRecorder() *recorder { return &recorder{} }
func (r *recorder) Start(_ context.Context, app string) error {
r.mu.Lock()
r.installs = append(r.installs, app)
r.mu.Unlock()
return nil
}
func (r *recorder) Uninstall(_ context.Context, app string) error {
r.mu.Lock()
r.uninstalls = append(r.uninstalls, app)
r.mu.Unlock()
return r.uninstallErr
}
func (r *recorder) counts() (int, int) {
r.mu.Lock()
defer r.mu.Unlock()
return len(r.installs), len(r.uninstalls)
}
const confirmCopy = "Uninstall Scratchpad? It's removed from Home for everyone at Acme. Its data is kept, and comes back if you install it again."
func contains(body, want string) bool {
return strings.Contains(body, want) || strings.Contains(body, strings.ReplaceAll(want, "'", "'"))
}
// Start is synchronous by contract (it only claims), so the handler calls
// it before redirecting. That the install then outlives the request is
// install.TestStartClaimsThenProvisionsInBackground's to prove.
func TestStoreInstallButtonPostsAndRedirects(t *testing.T) {
rec := newRecorder()
a := newAppWith(t, rec, time.UTC)
a.signedInOwner()
page := a.get("/store")
if page.Code != 200 || !strings.Contains(page.Body, `action="/store/scratchpad/install"`) {
t.Fatalf("store page lacks an install form: %d\n%s", page.Code, page.Body)
}
if r := a.post("/store/scratchpad/install", nil); r.Code != 303 || r.Location() != "/store" {
t.Fatalf("install: %d %q", r.Code, r.Location())
}
rec.mu.Lock()
got := append([]string(nil), rec.installs...)
rec.mu.Unlock()
if len(got) != 1 || got[0] != "scratchpad" {
t.Fatalf("Start calls = %q, want one for scratchpad", got)
}
if r := a.post("/store/nope/install", nil); r.Code != 404 {
t.Fatalf("unknown app: %d", r.Code)
}
}
func TestStoreShowsInstallingWithRefresh(t *testing.T) {
a := newApp(t)
a.signedInOwner()
if strings.Contains(a.get("/store").Body, `http-equiv="refresh"`) {
t.Fatal("refresh with nothing installing")
}
a.setInstall("scratchpad", "installing", "")
body := a.get("/store").Body
if !strings.Contains(body, ``) || strings.Contains(body, "