package handler

import (
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
)

func TestParseDateParam(t *testing.T) {
	gin.SetMode(gin.TestMode)

	t.Run("valid_date", func(t *testing.T) {
		w := httptest.NewRecorder()
		c, _ := gin.CreateTestContext(w)
		c.Request = httptest.NewRequest(http.MethodGet, "/?start_date=2024-01-15", nil)

		result, err := parseDateParam(c, "start_date")
		assert.NoError(t, err)
		assert.NotNil(t, result)
		expected := time.Date(2024, 1, 15, 0, 0, 0, 0, time.UTC)
		assert.Equal(t, expected, *result)
	})

	t.Run("empty_param", func(t *testing.T) {
		w := httptest.NewRecorder()
		c, _ := gin.CreateTestContext(w)
		c.Request = httptest.NewRequest(http.MethodGet, "/", nil)

		result, err := parseDateParam(c, "start_date")
		assert.NoError(t, err)
		assert.Nil(t, result)
	})

	t.Run("invalid_format", func(t *testing.T) {
		w := httptest.NewRecorder()
		c, _ := gin.CreateTestContext(w)
		c.Request = httptest.NewRequest(http.MethodGet, "/?start_date=2024/01/15", nil)

		result, err := parseDateParam(c, "start_date")
		assert.Error(t, err)
		assert.Nil(t, result)
		assert.Contains(t, err.Error(), "start_date")
		assert.Contains(t, err.Error(), "YYYY-MM-DD")
	})

	t.Run("end_date", func(t *testing.T) {
		w := httptest.NewRecorder()
		c, _ := gin.CreateTestContext(w)
		c.Request = httptest.NewRequest(http.MethodGet, "/?end_date=2024-12-31", nil)

		result, err := parseDateParam(c, "end_date")
		assert.NoError(t, err)
		assert.NotNil(t, result)
		expected := time.Date(2024, 12, 31, 0, 0, 0, 0, time.UTC)
		assert.Equal(t, expected, *result)
	})
}
