package handlers_test

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

	"github.com/rede5/gohorsejobs/backend/internal/api/handlers"
)

func TestNewLocationHandlers(t *testing.T) {
	h := handlers.NewLocationHandlers(nil)
	if h == nil {
		t.Error("NewLocationHandlers should not return nil")
	}
}

func TestListStatesByCountry_MissingID(t *testing.T) {
	h := handlers.NewLocationHandlers(nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/locations/countries/states", nil)
	rr := httptest.NewRecorder()

	h.ListStatesByCountry(rr, req)

	if rr.Code != http.StatusBadRequest {
		t.Errorf("Expected status 400, got %d", rr.Code)
	}
}

func TestListCitiesByState_MissingID(t *testing.T) {
	h := handlers.NewLocationHandlers(nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/locations/states/cities", nil)
	rr := httptest.NewRecorder()

	h.ListCitiesByState(rr, req)

	if rr.Code != http.StatusBadRequest {
		t.Errorf("Expected status 400, got %d", rr.Code)
	}
}

func TestSearchLocations_ShortQuery(t *testing.T) {
	h := handlers.NewLocationHandlers(nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/locations/search?q=a&country_id=1", nil)
	rr := httptest.NewRecorder()

	h.SearchLocations(rr, req)

	// Short query returns empty array
	if rr.Code != http.StatusOK {
		t.Errorf("Expected status 200, got %d", rr.Code)
	}
	if rr.Body.String() != "[]" {
		t.Errorf("Expected [], got %s", rr.Body.String())
	}
}

func TestSearchLocations_MissingCountryID(t *testing.T) {
	h := handlers.NewLocationHandlers(nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/locations/search?q=tokyo", nil)
	rr := httptest.NewRecorder()

	h.SearchLocations(rr, req)

	if rr.Code != http.StatusBadRequest {
		t.Errorf("Expected status 400, got %d", rr.Code)
	}
}

func TestSearchLocations_InvalidCountryID(t *testing.T) {
	h := handlers.NewLocationHandlers(nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/locations/search?q=tokyo&country_id=abc", nil)
	rr := httptest.NewRecorder()

	h.SearchLocations(rr, req)

	if rr.Code != http.StatusBadRequest {
		t.Errorf("Expected status 400, got %d", rr.Code)
	}
}
