package handlers

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestCalculate_MissingFields(t *testing.T) {
	h := &CalculateHandlers{}

	tests := []struct {
		name string
		body string
		want string
	}{
		{
			name: "empty body",
			body: `{}`,
			want: "proceeding_type and trigger_event_date are required",
		},
		{
			name: "missing trigger_event_date",
			body: `{"proceeding_type":"INF"}`,
			want: "proceeding_type and trigger_event_date are required",
		},
		{
			name: "missing proceeding_type",
			body: `{"trigger_event_date":"2026-06-01"}`,
			want: "proceeding_type and trigger_event_date are required",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			r := httptest.NewRequest("POST", "/api/deadlines/calculate", bytes.NewBufferString(tt.body))
			w := httptest.NewRecorder()

			h.Calculate(w, r)

			if w.Code != http.StatusBadRequest {
				t.Errorf("expected 400, got %d", w.Code)
			}
			var resp map[string]string
			json.NewDecoder(w.Body).Decode(&resp)
			if resp["error"] != tt.want {
				t.Errorf("expected error %q, got %q", tt.want, resp["error"])
			}
		})
	}
}

func TestCalculate_InvalidDateFormat(t *testing.T) {
	h := &CalculateHandlers{}
	body := `{"proceeding_type":"INF","trigger_event_date":"01-06-2026"}`
	r := httptest.NewRequest("POST", "/api/deadlines/calculate", bytes.NewBufferString(body))
	w := httptest.NewRecorder()

	h.Calculate(w, r)

	if w.Code != http.StatusBadRequest {
		t.Errorf("expected 400, got %d", w.Code)
	}
	var resp map[string]string
	json.NewDecoder(w.Body).Decode(&resp)
	if resp["error"] != "invalid trigger_event_date format, expected YYYY-MM-DD" {
		t.Errorf("unexpected error: %s", resp["error"])
	}
}

func TestCalculate_InvalidJSON(t *testing.T) {
	h := &CalculateHandlers{}
	r := httptest.NewRequest("POST", "/api/deadlines/calculate", bytes.NewBufferString(`not-json`))
	w := httptest.NewRecorder()

	h.Calculate(w, r)

	if w.Code != http.StatusBadRequest {
		t.Errorf("expected 400, got %d", w.Code)
	}
}
