package submit

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"testing/fstest"
	"time"

	"n2usenet/internal/config"
	"n2usenet/internal/storage"
)

func newTestApp(t *testing.T) *App {
	t.Helper()
	app, err := NewApp(config.Config{}, nil, storage.NewReplayCache(time.Minute), fstest.MapFS{}, "<!doctype html>")
	if err != nil {
		t.Fatalf("NewApp returned error: %v", err)
	}
	return app
}

func TestSuccessResponseJSONNoStore(t *testing.T) {
	app := newTestApp(t)
	req := httptest.NewRequest(http.MethodPost, "/submit", nil)
	req.Header.Set("Accept", "application/json")
	rec := httptest.NewRecorder()

	app.successResponse(rec, req, "<test@example.net>")

	if rec.Code != http.StatusOK {
		t.Fatalf("unexpected status: got %d want %d", rec.Code, http.StatusOK)
	}
	if got := rec.Header().Get("Cache-Control"); got != "no-store" {
		t.Fatalf("unexpected Cache-Control: %q", got)
	}
	if got := rec.Header().Get("Clear-Site-Data"); got != "\"storage\"" {
		t.Fatalf("unexpected Clear-Site-Data: %q", got)
	}
	if got := rec.Header().Get("Content-Type"); !strings.Contains(got, "application/json") {
		t.Fatalf("unexpected Content-Type: %q", got)
	}
	var body map[string]string
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("failed to decode response body: %v", err)
	}
	if body["messageId"] != "<test@example.net>" {
		t.Fatalf("unexpected messageId: %q", body["messageId"])
	}
}

func TestErrorResponseJSONNoStore(t *testing.T) {
	app := newTestApp(t)
	req := httptest.NewRequest(http.MethodPost, "/submit", nil)
	req.Header.Set("Accept", "application/json")
	rec := httptest.NewRecorder()

	app.errorResponse(rec, req, http.StatusBadRequest, "Validation failed.")

	if rec.Code != http.StatusBadRequest {
		t.Fatalf("unexpected status: got %d want %d", rec.Code, http.StatusBadRequest)
	}
	if got := rec.Header().Get("Cache-Control"); got != "no-store" {
		t.Fatalf("unexpected Cache-Control: %q", got)
	}
	if got := rec.Header().Get("Content-Type"); !strings.Contains(got, "application/json") {
		t.Fatalf("unexpected Content-Type: %q", got)
	}
	var body map[string]string
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("failed to decode response body: %v", err)
	}
	if body["error"] != "Validation failed." {
		t.Fatalf("unexpected error body: %q", body["error"])
	}
}
