package seo import ( "context" "encoding/json" "net/http" "net/http/httptest" "path/filepath" "strings" "testing" "time" "supermarket/internal/api/gsc" "supermarket/internal/db" ) func openDB(t *testing.T) *db.DB { t.Helper() d, err := db.Open(filepath.Join(t.TempDir(), "app.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) return d } var now = time.Date(2026, 11, 22, 8, 0, 0, 0, time.UTC) // fakeGSC answers like Search Console for one property, with data through // 2026-11-19. Every day: the home page gets 10 clicks of 100 impressions at // position 2; /bulking is shown 200 times at position 7.6 for "whey price // comparison" and 20 times for "bulking whey", with no clicks; Google hides // queries worth 2 home clicks a day. func fakeGSC(t *testing.T, calls *[]gsc.Query) *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer tok" { w.WriteHeader(http.StatusUnauthorized) return } if r.URL.Path == "/sites" { json.NewEncoder(w).Encode(map[string]any{"siteEntry": []any{ map[string]any{"siteUrl": "sc-domain:whey.example", "permissionLevel": "siteOwner"}, map[string]any{"siteUrl": "https://other.example/", "permissionLevel": "siteUnverifiedUser"}, }}) return } if !strings.HasSuffix(r.URL.Path, "/searchAnalytics/query") || !strings.Contains(r.URL.RawPath+r.URL.Path, "sc-domain") { t.Errorf("unexpected %s", r.URL) } var q gsc.Query json.NewDecoder(r.Body).Decode(&q) *calls = append(*calls, q) start, _ := time.Parse(dayFormat, q.StartDate) end, _ := time.Parse(dayFormat, q.EndDate) if last, _ := time.Parse(dayFormat, "2026-11-19"); end.After(last) { end = last } var rows []gsc.Row home, bulk := "https://whey.example/", "https://whey.example/bulking/" for d := start; !d.After(end); d = d.AddDate(0, 0, 1) { day := d.Format(dayFormat) switch strings.Join(q.Dimensions, ",") { case "date": rows = append(rows, gsc.Row{Keys: []string{day}, Clicks: 10, Impressions: 320, Position: 5.5}) case "date,page": rows = append(rows, gsc.Row{Keys: []string{day, home}, Clicks: 10, Impressions: 100, Position: 2}, gsc.Row{Keys: []string{day, bulk}, Clicks: 0, Impressions: 220, Position: 7.6}) case "date,page,query": rows = append(rows, gsc.Row{Keys: []string{day, home, "whey"}, Clicks: 8, Impressions: 90, Position: 2}, gsc.Row{Keys: []string{day, bulk, "whey price comparison"}, Clicks: 0, Impressions: 200, Position: 7.6}, gsc.Row{Keys: []string{day, bulk, "bulking whey"}, Clicks: 0, Impressions: 20, Position: 12}) } } json.NewEncoder(w).Encode(map[string]any{"rows": rows}) })) } func TestSyncAndWhatRanks(t *testing.T) { d := openDB(t) var calls []gsc.Query srv := fakeGSC(t, &calls) defer srv.Close() c := gsc.New(func(context.Context) (string, error) { return "tok", nil }).WithBase(srv.URL) sites, err := c.Sites(context.Background()) if err != nil || len(sites) != 1 || sites[0].URL != "sc-domain:whey.example" { t.Fatalf("sites: %+v %v", sites, err) } if r, _ := WhatRanks(d, Scope{Property: "sc-domain:whey.example"}); r != nil { t.Error("ranks before any data") } res, err := Sync(context.Background(), d, c, "sc-domain:whey.example", now) if err != nil { t.Fatal(err) } if res.Through != "2026-11-19" || res.From != "2025-07-30" || len(calls) != 3*17 { t.Fatalf("sync: %+v, %d calls", res, len(calls)) } // The next sync reads only the last days again. calls = nil res, _ = Sync(context.Background(), d, c, "sc-domain:whey.example", now.AddDate(0, 0, 1)) if res.From != "2026-11-15" || len(calls) != 3 || calls[0].DataState != "final" { t.Errorf("second sync: %+v %+v", res, calls) } if last, _ := LastSync(d, "sc-domain:whey.example"); last == nil || last.Through != "2026-11-19" { t.Errorf("last sync: %+v", last) } r, err := WhatRanks(d, Scope{Property: "sc-domain:whey.example"}) if err != nil { t.Fatal(err) } if r.From != "2026-08-22" || r.To != "2026-11-19" || r.Total.Clicks != 900 || r.Total.Impressions != 28800 || r.Total.Position != 5.5 { t.Errorf("totals: %+v", r) } if int(r.Anonymous+0.5) != 20 { t.Errorf("anonymous share: %v", r.Anonymous) } if len(r.Pages) != 2 || r.Pages[0].Page != "https://whey.example/" || r.Pages[0].CTR() != 10 { t.Errorf("pages: %+v", r.Pages) } if len(r.Unclicked) != 2 || r.Unclicked[0].Query != "whey price comparison" || r.Unclicked[0].Impressions != 18000 { t.Errorf("unclicked: %+v", r.Unclicked) } if len(r.Protect) != 1 || !strings.Contains(r.Protect[0].Why, "100.0% of all clicks") { t.Errorf("protect: %+v", r.Protect) } if len(r.Push) != 1 { t.Fatalf("push: %+v", r.Push) } p := r.Push[0] if p.Page != "https://whey.example/bulking/" || p.MainQuery != "whey price comparison" || int(p.MainShare+0.5) != 91 || !strings.Contains(p.Why, "Shown 19,800 times at position 7.6, 0 clicks. 91% of its impressions come from “whey price comparison”, where it's at 7.6.") { t.Errorf("push: %+v", p) } }