package server

import (
	"context"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

type stubStripeSyncer struct {
	from time.Time
	to   time.Time
	err  error
}

func (s *stubStripeSyncer) SyncStripePayments(ctx context.Context, from, to time.Time) error {
	s.from = from
	s.to = to
	return s.err
}

func TestHandleStripeSyncSuccess(t *testing.T) {
	syncer := &stubStripeSyncer{}
	handler := handleStripeSync(syncer)

	now := time.Now().UTC().Truncate(time.Second)
	from := now.Add(-2 * time.Hour).Format(time.RFC3339)
	to := now.Format(time.RFC3339)

	req := httptest.NewRequest(http.MethodPost, "/api/stripe/sync", strings.NewReader(`{"from":"`+from+`","to":"`+to+`"}`))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()

	handler(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("expected status 200, got %d", rec.Code)
	}

	if syncer.from.IsZero() || syncer.to.IsZero() {
		t.Fatal("expected syncer to receive time bounds")
	}
}

func TestHandleStripeSyncInvalidTimestamp(t *testing.T) {
	syncer := &stubStripeSyncer{}
	handler := handleStripeSync(syncer)

	req := httptest.NewRequest(http.MethodPost, "/api/stripe/sync", strings.NewReader(`{"from":"not-a-date"}`))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()

	handler(rec, req)

	if rec.Code != http.StatusBadRequest {
		t.Fatalf("expected status 400, got %d", rec.Code)
	}
}
