// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: LicenseRef-MutuaL-1.2

package cooked

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"
)

func TestReadShoppingListACIDAuthenticationLogin3StoresCookies(t *testing.T) {
	var sawSessionCookie bool

	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/api/public/login":
			if r.Method != http.MethodPost {
				t.Fatalf("login method = %s, want POST", r.Method)
			}

			var request loginRequest
			if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
				t.Fatalf("decode login request: %v", err)
			}
			if request.Username != "configured-user" || request.Password != "configured-password" {
				t.Fatalf("login request = %#v, want configured credentials", request)
			}

			http.SetCookie(w, &http.Cookie{Name: "cooked_session", Value: "session-value", Path: "/"})
			writeJSON(t, w, loginResponse{Username: "returned-user"})
		case "/api/user/returned-user/shopping-list":
			cookie, err := r.Cookie("cooked_session")
			if err != nil {
				t.Fatalf("missing session cookie: %v", err)
			}
			if cookie.Value != "session-value" {
				t.Fatalf("session cookie = %q, want session-value", cookie.Value)
			}
			sawSessionCookie = true
			writeJSON(t, w, shoppingListResponse{
				ShoppingList: ShoppingList{
					Aisles: []Aisle{{
						ID:   "pantry",
						Name: "Pantry",
						ProductGroups: []ProductGroup{{
							ID:       "pasta",
							Name:     "Pasta",
							Quantity: "200g",
						}},
					}},
				},
				Recipes: []string{"recipe-id"},
			})
		default:
			t.Fatalf("unexpected path %s", r.URL.Path)
		}
	}))
	defer server.Close()

	baseURL, err := url.Parse(server.URL)
	if err != nil {
		t.Fatalf("parse server URL: %v", err)
	}
	client, err := NewClient(baseURL, "configured-user", "configured-password")
	if err != nil {
		t.Fatalf("NewClient() error = %v", err)
	}

	shoppingList, err := client.ReadShoppingList(context.Background())
	if err != nil {
		t.Fatalf("ReadShoppingList() error = %v", err)
	}

	if !sawSessionCookie {
		t.Fatal("shopping-list request did not receive session cookie")
	}
	if len(shoppingList.Aisles) != 1 || shoppingList.Aisles[0].ProductGroups[0].Name != "Pasta" {
		t.Fatalf("shopping list = %#v, want one Pasta item", shoppingList)
	}
}

func TestUserPathEscapesAuthenticatedUsername(t *testing.T) {
	client := &Client{authenticatedUsername: "user/name"}

	got := client.userPath("/api/user/{username}/shopping-list")
	if got != "/api/user/user%2Fname/shopping-list" {
		t.Fatalf("userPath() = %q, want escaped username", got)
	}
}

func writeJSON[T loginResponse | shoppingListResponse](t *testing.T, w http.ResponseWriter, value T) {
	t.Helper()

	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(value); err != nil {
		t.Fatalf("write JSON: %v", err)
	}
}
