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

package cooked

import (
	"context"
	"net/http"
	"testing"
)

func TestPreviewRecipeTextACIDAPIClientResponses1AcceptsIntegerDecimalPortions(t *testing.T) {
	var previewCalls int
	client, closeServer := newTestClient(t, rawPreviewRecipeTextTestHandler(
		t,
		&previewCalls,
		"{\"title\":\"Pasta\",\"markdown\":\"# Pasta\",\"portions\":1.0}",
	))
	defer closeServer()

	preview, err := client.PreviewRecipeText(context.Background(), "Pasta", "Boil pasta.")
	if err != nil {
		t.Fatalf("PreviewRecipeText() error = %v", err)
	}
	if previewCalls != 1 {
		t.Fatalf("preview calls = %d, want 1", previewCalls)
	}
	if preview.Portions != 1 {
		t.Fatalf("preview portions = %g, want 1", preview.Portions)
	}
}

// api-client.RESPONSES.1 recipes.PREVIEW_TEXT.4-1
func TestPreviewRecipeTextACIDAPIClientResponses1AndRecipesPreviewText4_1PreservesFractionalPortions(t *testing.T) {
	var previewCalls int
	client, closeServer := newTestClient(t, rawPreviewRecipeTextTestHandler(
		t,
		&previewCalls,
		"{\"title\":\"Pasta\",\"markdown\":\"# Pasta\",\"portions\":1.5}",
	))
	defer closeServer()

	preview, err := client.PreviewRecipeText(context.Background(), "Pasta", "Boil pasta.")
	if err != nil {
		t.Fatalf("PreviewRecipeText() error = %v", err)
	}
	if previewCalls != 1 {
		t.Fatalf("preview calls = %d, want 1", previewCalls)
	}
	if preview.Portions != 1.5 {
		t.Fatalf("preview portions = %g, want 1.5", preview.Portions)
	}
}

func rawPreviewRecipeTextTestHandler(t *testing.T, previewCalls *int, body string) http.HandlerFunc {
	t.Helper()

	return func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/api/public/login":
			writeLoginResponse(t, w)
		case "/api/new/from-text/preview":
			requireMethod(t, r, http.MethodPost, "preview")
			requireSessionCookie(t, r)
			requirePreviewRecipeTextRequest(t, r)
			(*previewCalls)++
			w.Header().Set("Content-Type", "application/json")
			if _, err := w.Write([]byte(body)); err != nil {
				t.Fatalf("write raw preview response: %v", err)
			}
		default:
			t.Fatalf("unexpected path %s", r.URL.Path)
		}
	}
}
