package platform

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"
)

func TestHandlerDashboardSummary(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/dashboard/summary", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "onlineVehicles") {
		t.Fatalf("response missing onlineVehicles: %s", rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "serviceStatuses") || !strings.Contains(rec.Body.String(), "degraded") {
		t.Fatalf("response missing vehicle service status distribution: %s", rec.Body.String())
	}
}

func TestHandlerV2MonitorSummaryAndMap(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	for _, test := range []struct {
		path string
		want string
	}{
		{path: "/api/v2/monitor/summary", want: "drivingVehicles"},
		{path: "/api/v2/monitor/map?zoom=5", want: "clusters"},
		{path: "/api/v2/monitor/map?zoom=11", want: "points"},
	} {
		rec := httptest.NewRecorder()
		req := httptest.NewRequest(http.MethodGet, test.path, nil)
		handler.ServeHTTP(rec, req)
		if rec.Code != http.StatusOK {
			t.Fatalf("%s status = %d body=%s", test.path, rec.Code, rec.Body.String())
		}
		if !strings.Contains(rec.Body.String(), test.want) {
			t.Fatalf("%s missing %q: %s", test.path, test.want, rec.Body.String())
		}
		if test.path == "/api/v2/monitor/summary" && (!strings.Contains(rec.Body.String(), `"alertDataAvailable":true`) || !strings.Contains(rec.Body.String(), `"alertVehicles":1`)) {
			t.Fatalf("monitor summary must expose filtered active alert vehicles: %s", rec.Body.String())
		}
	}
}

func TestHandlerRejectsInvalidMonitorBounds(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	request := httptest.NewRequest(http.MethodGet, "/api/v2/monitor/map?zoom=12&bounds=105,31,103,29", nil)
	response := httptest.NewRecorder()
	handler.ServeHTTP(response, request)
	if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "MONITOR_BOUNDS_INVALID") {
		t.Fatalf("unexpected invalid bounds response: status=%d body=%s", response.Code, response.Body.String())
	}
}

func TestHandlerV2AccessManagement(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	for _, test := range []struct {
		method string
		path   string
		body   string
		want   string
	}{
		{method: http.MethodPost, path: "/api/v2/access/summary", body: `{}`, want: `"neverReported":1`},
		{method: http.MethodPost, path: "/api/v2/access/vehicles", body: `{"onlineState":"offline","limit":10}`, want: `"onlineState":"offline"`},
		{method: http.MethodGet, path: "/api/v2/access/thresholds", want: `"defaultThresholdSec":300`},
		{method: http.MethodPut, path: "/api/v2/access/thresholds", body: `{"version":1,"defaultThresholdSec":600,"delayThresholdSec":60,"longOfflineSec":3600,"protocols":[{"protocol":"JT808","thresholdSec":300}],"actor":"handler-test"}`, want: `"version":2`},
	} {
		rec := httptest.NewRecorder()
		req := httptest.NewRequest(test.method, test.path, strings.NewReader(test.body))
		handler.ServeHTTP(rec, req)
		if rec.Code != http.StatusOK {
			t.Fatalf("%s %s status=%d body=%s", test.method, test.path, rec.Code, rec.Body.String())
		}
		if !strings.Contains(rec.Body.String(), test.want) {
			t.Fatalf("%s %s missing %s body=%s", test.method, test.path, test.want, rec.Body.String())
		}
	}
}

func TestHandlerV2TrackPlayback(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/v2/tracks?keyword=%E5%B7%9DAHTWO1&maxPoints=8", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data TrackPlaybackResponse `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.VIN != "LNXNEGRR7SR318212" || body.Data.Summary.PointCount < 10 {
		t.Fatalf("track should resolve vehicle and summarize full point set: %+v", body.Data)
	}
	if len(body.Data.Points) != 8 || !body.Data.Sampled {
		t.Fatalf("track should server-sample map payload to requested bound: %+v", body.Data)
	}
	if len(body.Data.Events) < 2 || len(body.Data.Sources) != 1 {
		t.Fatalf("track should expose events and source evidence: %+v", body.Data)
	}
}

func TestHandlerV2HistoryCatalogAndMultiVehicleQuery(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	for _, test := range []struct{ path, want string }{
		{path: "/api/v2/metrics", want: "sourceFields"},
		{path: "/api/v2/vehicles/%E5%B7%9DAHTWO1/telemetry/latest", want: "sourceField"},
		{path: "/api/v2/history/metrics", want: "dailyMileageKm"},
		{path: "/api/v2/history/query?keywords=%E5%B7%9DAHTWO1,%E7%B2%A4AG18312&category=location&limit=10", want: "queryDurationMs"},
		{path: "/api/v2/history/query?keyword=%E5%B7%9DAHTWO1&category=raw&limit=10", want: "gb32960.vehicle.speed_kmh"},
		{path: "/api/v2/history/series?keyword=%E5%B7%9DAHTWO1&dateFrom=2026-07-03T18%3A00&dateTo=2026-07-03T21%3A00&targetPoints=120", want: "grainSeconds"},
	} {
		rec := httptest.NewRecorder()
		req := httptest.NewRequest(http.MethodGet, test.path, nil)
		handler.ServeHTTP(rec, req)
		if rec.Code != http.StatusOK {
			t.Fatalf("%s status=%d body=%s", test.path, rec.Code, rec.Body.String())
		}
		if !strings.Contains(rec.Body.String(), test.want) {
			t.Fatalf("%s missing %q body=%s", test.path, test.want, rec.Body.String())
		}
	}
}

func TestHistorySeriesGrainAndBounds(t *testing.T) {
	if got := historySeriesGrain(24*time.Hour, 240); got != 900 {
		t.Fatalf("24h / 240 should select the next safe nice bucket, got %d", got)
	}
	handler := NewHandler(NewService(NewMockStore()))
	for _, test := range []struct{ path, code string }{
		{path: "/api/v2/history/series?category=raw&keyword=%E5%B7%9DAHTWO1", code: "HISTORY_SERIES_CATEGORY_UNSUPPORTED"},
		{path: "/api/v2/history/series?keyword=%E5%B7%9DAHTWO1&dateFrom=2026-01-01T00%3A00&dateTo=2026-03-01T00%3A00", code: "HISTORY_TIME_RANGE_TOO_LARGE"},
	} {
		rec := httptest.NewRecorder()
		handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, test.path, nil))
		if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), test.code) {
			t.Fatalf("%s expected %s, status=%d body=%s", test.path, test.code, rec.Code, rec.Body.String())
		}
	}
}

func TestHandlerV2HistoryRequiresBoundedVehicleScope(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/v2/history/query?category=location", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "VEHICLE_KEY_REQUIRED") {
		t.Fatalf("unbounded history query should be rejected: status=%d body=%s", rec.Code, rec.Body.String())
	}
}

func TestHandlerVehicles(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles?limit=10", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
		t.Fatalf("response missing vehicle: %s", rec.Body.String())
	}
	var body struct {
		Data Page[VehicleRow] `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if len(body.Data.Items) == 0 || body.Data.Items[0].ServiceStatus == nil {
		t.Fatalf("vehicle row should include canonical vehicle service status: %s", rec.Body.String())
	}
	if body.Data.Items[0].ServiceStatus.Status != "degraded" {
		t.Fatalf("vehicle row should expose degraded status, got %+v", body.Data.Items[0].ServiceStatus)
	}
}

func TestHandlerVehiclesFiltersServiceStatus(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles?limit=10&serviceStatus=degraded", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
		t.Fatalf("degraded vehicles should include partially online vehicle: %s", rec.Body.String())
	}
	if strings.Contains(rec.Body.String(), "LMRKH9AC2R1004087") {
		t.Fatalf("degraded vehicles should exclude healthy vehicle: %s", rec.Body.String())
	}
}

func TestHandlerVehicleCoverage(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/coverage?limit=10&coverage=multi&online=online&bindingStatus=bound", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	for _, want := range []string{"sourceCount", "onlineSourceCount", "protocols", "LB9A32A24R0LS1426"} {
		if !strings.Contains(rec.Body.String(), want) {
			t.Fatalf("response missing %q: %s", want, rec.Body.String())
		}
	}
	var body struct {
		Data Page[VehicleCoverageRow] `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if len(body.Data.Items) == 0 || body.Data.Items[0].ServiceStatus == nil {
		t.Fatalf("coverage row should include canonical vehicle service status: %s", rec.Body.String())
	}
	if body.Data.Items[0].ServiceStatus.Status != "degraded" {
		t.Fatalf("coverage row should expose degraded status, got %+v", body.Data.Items[0].ServiceStatus)
	}
	var rawBody struct {
		Data Page[struct {
			VIN               string                    `json:"vin"`
			MissingProtocols  []string                  `json:"missingProtocols"`
			SourceStatus      []VehicleSourceStatus     `json:"sourceStatus"`
			SourceConsistency *VehicleSourceConsistency `json:"sourceConsistency"`
		}] `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &rawBody); err != nil {
		t.Fatalf("response JSON should decode missing source evidence: %v body=%s", err, rec.Body.String())
	}
	if len(rawBody.Data.Items) == 0 || !containsString(rawBody.Data.Items[0].MissingProtocols, "YUTONG_MQTT") {
		t.Fatalf("coverage row should expose missing canonical protocols, got %+v body=%s", rawBody.Data.Items, rec.Body.String())
	}
	if len(rawBody.Data.Items) == 0 || rawBody.Data.Items[0].SourceConsistency == nil {
		t.Fatalf("coverage row should expose vehicle-level source consistency: %s", rec.Body.String())
	}
	if rawBody.Data.Items[0].SourceConsistency.Status != "degraded" || !containsString(rawBody.Data.Items[0].SourceConsistency.MissingProtocols, "YUTONG_MQTT") {
		t.Fatalf("coverage source consistency should diagnose missing source evidence, got %+v body=%s", rawBody.Data.Items[0].SourceConsistency, rec.Body.String())
	}
	byProtocol := map[string]VehicleSourceStatus{}
	for _, source := range rawBody.Data.Items[0].SourceStatus {
		byProtocol[source.Protocol] = source
	}
	for _, protocol := range []string{"GB32960", "JT808", "YUTONG_MQTT"} {
		if _, ok := byProtocol[protocol]; !ok {
			t.Fatalf("coverage row should expose canonical source slot %s, got %+v body=%s", protocol, rawBody.Data.Items[0].SourceStatus, rec.Body.String())
		}
	}
	if !byProtocol["JT808"].Online || byProtocol["YUTONG_MQTT"].Online || byProtocol["YUTONG_MQTT"].HasRealtime {
		t.Fatalf("coverage source slots should expose online and missing evidence, got %+v", byProtocol)
	}
}

func TestHandlerVehicleCoverageFiltersServiceStatus(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/coverage?limit=10&serviceStatus=degraded", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
		t.Fatalf("degraded coverage should include partially online multi-source vehicle: %s", rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "LMRKH9AC2R1004087") {
		t.Fatalf("degraded coverage should include online single-source vehicle that misses canonical sources: %s", rec.Body.String())
	}
}

func TestHandlerVehicleCoverageFiltersMissingProtocol(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/coverage?limit=10&missingProtocol=YUTONG_MQTT", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
		t.Fatalf("missing MQTT coverage should include vehicle without MQTT source: %s", rec.Body.String())
	}
	if strings.Contains(rec.Body.String(), "LMRKH9AC2R1004087") {
		t.Fatalf("missing MQTT coverage should exclude vehicle with MQTT source: %s", rec.Body.String())
	}
}

func TestHandlerVehicleCoverageTreatsMissingCanonicalSourceAsDegraded(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/coverage?limit=10&missingProtocol=YUTONG_MQTT&online=online", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data Page[VehicleCoverageRow] `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if len(body.Data.Items) == 0 {
		t.Fatalf("missing source query should return online vehicles with missing canonical source: %s", rec.Body.String())
	}
	for _, row := range body.Data.Items {
		if row.ServiceStatus == nil || row.ServiceStatus.Status != "degraded" {
			t.Fatalf("missing canonical source should degrade vehicle service, got row=%+v body=%s", row, rec.Body.String())
		}
		if row.ServiceStatus.Title != "来源不完整" {
			t.Fatalf("missing canonical source should use explicit incomplete-source title, got row=%+v body=%s", row, rec.Body.String())
		}
	}
}

func TestHandlerVehicleCoverageSummary(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/coverage/summary?coverage=multi", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleCoverageSummary `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.TotalVehicles != 1 || body.Data.MultiSourceVehicles != 1 {
		t.Fatalf("coverage summary should honor filters, got %+v body=%s", body.Data, rec.Body.String())
	}
	if body.Data.OnlineVehicles != 1 || body.Data.UnboundVehicles != 0 {
		t.Fatalf("coverage summary should expose filtered online and binding totals, got %+v", body.Data)
	}
	if len(body.Data.MissingSources) == 0 {
		t.Fatalf("coverage summary should expose missing source counts, got %+v", body.Data)
	}
	if len(body.Data.ArchiveMissingFields) == 0 {
		t.Fatalf("coverage summary should expose archive missing-field counts, got %+v", body.Data)
	}
}

func TestSplitCSVEmptyReturnsEmptySlice(t *testing.T) {
	values := splitCSV("")
	if values == nil {
		t.Fatalf("empty CSV should encode as [] instead of JSON null")
	}
	if len(values) != 0 {
		t.Fatalf("empty CSV should have no values, got %#v", values)
	}
}

func TestHandlerVehicleDetail(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/detail?vin=LB9A32A24R0LS1426", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	for _, want := range []string{"lookupKey", "lookupResolved", "identity", "realtimeSummary", "realtime", "history", "raw", "mileage", "quality", "sources", "sourceStatus"} {
		if !strings.Contains(rec.Body.String(), want) {
			t.Fatalf("response missing %q: %s", want, rec.Body.String())
		}
	}
}

func TestHandlerVehicleSourceEvidence(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/v2/vehicles/LB9A32A24R0LS1426/source-evidence?date=2026-07-16", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleSourceEvidence `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.VIN != "LB9A32A24R0LS1426" || body.Data.MileageDate != "2026-07-16" {
		t.Fatalf("unexpected source evidence identity: %+v", body.Data)
	}
	if len(body.Data.LocationSources) != 3 || len(body.Data.MileageSources) != 2 {
		t.Fatalf("source evidence should expose all mock candidates: %+v", body.Data)
	}
	recommended := 0
	for _, source := range body.Data.LocationSources {
		if source.Recommended {
			recommended++
		}
		if strings.Contains(source.TerminalLabel, "13307795425") {
			t.Fatalf("source evidence must not expose a raw terminal identifier: %+v", source)
		}
	}
	if recommended != 1 || body.Data.RecommendedLocationProtocol != "JT808" {
		t.Fatalf("source evidence should align with realtime election: %+v", body.Data)
	}
	if body.Data.Comparison.LocationMaxDistanceM <= 0 || body.Data.Comparison.TotalMileageDeltaKm <= 0 {
		t.Fatalf("source evidence should calculate cross-source deltas: %+v", body.Data.Comparison)
	}
}

func TestHandlerVehicleSourceEvidenceRejectsInvalidDate(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/v2/vehicles/LB9A32A24R0LS1426/source-evidence?date=16-07-2026", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "INVALID_DATE") {
		t.Fatalf("unexpected invalid date response: status=%d body=%s", rec.Code, rec.Body.String())
	}
}

func TestHandlerVehicleSourceDiagnosticAndPolicyUpdate(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	ctx := WithPrincipal(context.Background(), Principal{Name: "平台管理员", Role: "admin", UserType: "admin"})
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/v2/operations/vehicles/LB9A32A24R0LS1426/sources", nil).WithContext(ctx)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("diagnostic status=%d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleSourceDiagnostic `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatal(err)
	}
	source := body.Data.Evidence.LocationSources[1]
	payload := fmt.Sprintf(`{"version":%d,"enabled":false,"priority":%d,"remark":"人工核验"}`, body.Data.Policy.Version, source.Priority)
	rec = httptest.NewRecorder()
	req = httptest.NewRequest(http.MethodPut, "/api/v2/operations/vehicles/LB9A32A24R0LS1426/sources/"+source.SourceRef, strings.NewReader(payload)).WithContext(ctx)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"version":2`) {
		t.Fatalf("policy update status=%d body=%s", rec.Code, rec.Body.String())
	}
}

func TestHandlerVehicleServiceCanonicalEndpoint(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312&protocol=JT808", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleDetail `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.Resolution == nil || body.Data.Resolution.VIN != "LB9A32A24R0LS1426" {
		t.Fatalf("vehicle service should resolve canonical vehicle identity, got %+v body=%s", body.Data.Resolution, rec.Body.String())
	}
	for _, row := range body.Data.Realtime {
		if row.Protocol != "JT808" {
			t.Fatalf("vehicle service should keep source filter, got realtime row %+v body=%s", row, rec.Body.String())
		}
	}
}

func TestHandlerVehicleServiceIncludesVehicleLevelStatus(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleDetail `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.ServiceStatus == nil {
		t.Fatalf("vehicle service should include serviceStatus: %s", rec.Body.String())
	}
	if body.Data.ServiceStatus.Status != "degraded" || body.Data.ServiceStatus.Title != "来源不完整" {
		t.Fatalf("vehicle service should prioritize missing source evidence, got %+v body=%s", body.Data.ServiceStatus, rec.Body.String())
	}
	if body.Data.ServiceStatus.OnlineSourceCount != 1 || body.Data.ServiceStatus.SourceCount != 3 {
		t.Fatalf("vehicle service should expose source counts, got %+v body=%s", body.Data.ServiceStatus, rec.Body.String())
	}
	if body.Data.Resolution == nil || body.Data.Resolution.ServiceStatus == nil || body.Data.Resolution.ServiceStatus.Title != body.Data.ServiceStatus.Title {
		t.Fatalf("resolution should reuse canonical vehicle service status, resolution=%+v service=%+v", body.Data.Resolution, body.Data.ServiceStatus)
	}
	if body.Data.Identity == nil || body.Data.Identity.ServiceStatus == nil || body.Data.Identity.ServiceStatus.Title != body.Data.ServiceStatus.Title {
		t.Fatalf("identity should reuse canonical vehicle service status, identity=%+v service=%+v", body.Data.Identity, body.Data.ServiceStatus)
	}
	if body.Data.RealtimeSummary == nil || body.Data.RealtimeSummary.ServiceStatus == nil || body.Data.RealtimeSummary.ServiceStatus.Title != body.Data.ServiceStatus.Title {
		t.Fatalf("realtime summary should reuse canonical vehicle service status, summary=%+v service=%+v", body.Data.RealtimeSummary, body.Data.ServiceStatus)
	}
}

func TestHandlerVehicleServiceIncludesUnifiedOverview(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleDetail `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.ServiceOverview == nil {
		t.Fatalf("vehicle service should include serviceOverview: %s", rec.Body.String())
	}
	overview := body.Data.ServiceOverview
	if overview.VIN != "LB9A32A24R0LS1426" || overview.Plate != "粤AG18312" {
		t.Fatalf("overview should expose canonical vehicle identity, got %+v", overview)
	}
	if overview.SourceCount != 3 || overview.OnlineSourceCount != 1 || overview.CoverageStatus != "partial" {
		t.Fatalf("overview should summarize source coverage, got %+v", overview)
	}
	if overview.LastSeen == "" || overview.PrimaryProtocol == "" {
		t.Fatalf("overview should expose latest service time and primary source, got %+v", overview)
	}
	if overview.RealtimeCount == 0 || overview.HistoryCount == 0 || overview.RawCount == 0 || overview.MileageCount == 0 {
		t.Fatalf("overview should expose available data counts, got %+v", overview)
	}
}

func TestHandlerVehicleServiceIncludesSourceConsistency(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleDetail `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.SourceConsistency == nil {
		t.Fatalf("vehicle service should include sourceConsistency: %s", rec.Body.String())
	}
	consistency := body.Data.SourceConsistency
	if consistency.SourceCount != 3 || consistency.OnlineSourceCount != 1 || consistency.LocatedSourceCount != 2 {
		t.Fatalf("sourceConsistency should summarize source coverage, got %+v", consistency)
	}
	if consistency.MileageDeltaKm <= 0 || consistency.SourceTimeDeltaSeconds <= 0 {
		t.Fatalf("sourceConsistency should expose mileage and source time deltas, got %+v", consistency)
	}
	if consistency.Status == "" || consistency.Severity == "" || consistency.Title == "" || consistency.Detail == "" {
		t.Fatalf("sourceConsistency should expose actionable diagnosis, got %+v", consistency)
	}
	if consistency.Status != "degraded" || consistency.Title != "来源不完整" {
		t.Fatalf("sourceConsistency should diagnose missing source evidence before offline evidence, got %+v", consistency)
	}
}

func TestHandlerVehicleServiceExposesMissingSourceSlots(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleDetail `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	byProtocol := map[string]VehicleSourceStatus{}
	for _, source := range body.Data.SourceStatus {
		byProtocol[source.Protocol] = source
	}
	for _, protocol := range []string{"GB32960", "JT808", "YUTONG_MQTT"} {
		if _, ok := byProtocol[protocol]; !ok {
			t.Fatalf("vehicle service should expose expected source slot %s, got %+v", protocol, body.Data.SourceStatus)
		}
	}
	mqtt := byProtocol["YUTONG_MQTT"]
	if mqtt.Online || mqtt.HasRealtime || mqtt.HasHistory || mqtt.HasRaw || mqtt.HasMileage || mqtt.LastSeen != "" {
		t.Fatalf("missing MQTT source should be an empty coverage slot, got %+v", mqtt)
	}
}

func TestHandlerVehicleServiceConsistencyExposesMissingProtocols(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data struct {
			SourceConsistency struct {
				MissingProtocols []string `json:"missingProtocols"`
			} `json:"sourceConsistency"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if !containsString(body.Data.SourceConsistency.MissingProtocols, "YUTONG_MQTT") {
		t.Fatalf("sourceConsistency should expose missing source evidence, got %+v body=%s", body.Data.SourceConsistency.MissingProtocols, rec.Body.String())
	}
}

func TestHandlerVehicleServiceOverviewEndpoint(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service/overview?keyword=粤AG18312", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleServiceOverview `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.VIN != "LB9A32A24R0LS1426" || body.Data.Plate != "粤AG18312" {
		t.Fatalf("overview endpoint should resolve canonical vehicle identity, got %+v", body.Data)
	}
	if body.Data.SourceCount != 2 || body.Data.OnlineSourceCount != 1 || body.Data.CoverageStatus != "partial" {
		t.Fatalf("overview endpoint should summarize vehicle service coverage, got %+v", body.Data)
	}
	if body.Data.ServiceStatus == nil || body.Data.ServiceStatus.Status != "degraded" || body.Data.ServiceStatus.Title != "来源不完整" {
		t.Fatalf("overview endpoint should expose canonical service status, got %+v", body.Data.ServiceStatus)
	}
	if body.Data.SourceConsistency == nil || body.Data.SourceConsistency.SourceCount != 2 || body.Data.SourceConsistency.OnlineSourceCount != 1 {
		t.Fatalf("overview endpoint should expose source consistency, got %+v", body.Data.SourceConsistency)
	}
	if body.Data.SourceConsistency.Status != "degraded" || body.Data.SourceConsistency.Title != "来源不完整" {
		t.Fatalf("overview source consistency should expose diagnosis, got %+v", body.Data.SourceConsistency)
	}
	if strings.Contains(rec.Body.String(), `"raw"`) || strings.Contains(rec.Body.String(), `"history"`) {
		t.Fatalf("overview endpoint should not return heavy detail pages: %s", rec.Body.String())
	}
}

func TestHandlerVehicleServiceSummaryEndpoint(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service/summary", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleServiceSummary `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.TotalVehicles < 4 || body.Data.OnlineVehicles < 1 {
		t.Fatalf("summary should expose vehicle-level totals, got %+v", body.Data)
	}
	if body.Data.MultiSourceVehicles < 1 || body.Data.SingleSourceVehicles < 1 {
		t.Fatalf("summary should expose source coverage distribution, got %+v", body.Data)
	}
	if body.Data.ArchiveIncompleteVehicles < 1 {
		t.Fatalf("summary should expose incomplete archive vehicles, got %+v", body.Data)
	}
	if len(body.Data.ServiceStatuses) == 0 || len(body.Data.Protocols) == 0 {
		t.Fatalf("summary should expose service status and protocol distributions, got %+v", body.Data)
	}
	noDataStatusFound := false
	for _, status := range body.Data.ServiceStatuses {
		if status.Status == "degraded" && status.Title != "来源不完整" {
			t.Fatalf("summary degraded status should use vehicle-service missing source title, got %+v", status)
		}
		if status.Status == "no_data" {
			noDataStatusFound = true
			if status.Title != "暂无数据来源" || status.Count != body.Data.NoDataVehicles {
				t.Fatalf("no_data service status should mirror noDataVehicles, got status=%+v summary=%+v", status, body.Data)
			}
		}
	}
	if !noDataStatusFound {
		t.Fatalf("summary service status distribution should include no_data, got %+v", body.Data.ServiceStatuses)
	}
	var rawBody struct {
		Data struct {
			MissingSources []struct {
				Protocol string `json:"protocol"`
				Count    int    `json:"count"`
			} `json:"missingSources"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &rawBody); err != nil {
		t.Fatalf("response JSON should decode raw summary: %v body=%s", err, rec.Body.String())
	}
	missing := map[string]int{}
	for _, source := range rawBody.Data.MissingSources {
		missing[source.Protocol] = source.Count
	}
	if missing["GB32960"] != 2 || missing["JT808"] != 2 || missing["YUTONG_MQTT"] != 3 {
		t.Fatalf("summary should expose canonical missing source counts, got %+v body=%s", missing, rec.Body.String())
	}
}

func TestHandlerVehicleServiceOverviewsEndpoint(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodPost, "/api/vehicle-service/overviews", bytes.NewBufferString(`{"keywords":["粤AG18312","LMRKH9AC2R1004087"]}`))
	req.Header.Set("Content-Type", "application/json")
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data Page[VehicleServiceOverview] `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.Total != 2 || len(body.Data.Items) != 2 {
		t.Fatalf("batch overview should return two items, got %+v body=%s", body.Data, rec.Body.String())
	}
	if body.Data.Items[0].VIN != "LB9A32A24R0LS1426" || body.Data.Items[1].VIN != "LMRKH9AC2R1004087" {
		t.Fatalf("batch overview should preserve request order, got %+v", body.Data.Items)
	}
	if body.Data.Items[0].ServiceStatus == nil || body.Data.Items[1].ServiceStatus == nil {
		t.Fatalf("batch overview should include canonical status for every vehicle, got %+v", body.Data.Items)
	}
	if body.Data.Items[0].SourceConsistency == nil || body.Data.Items[0].SourceConsistency.SourceCount != 2 {
		t.Fatalf("batch overview should include source consistency, got %+v", body.Data.Items[0].SourceConsistency)
	}
	if strings.Contains(rec.Body.String(), `"raw"`) || strings.Contains(rec.Body.String(), `"history"`) {
		t.Fatalf("batch overview should not return heavy detail pages: %s", rec.Body.String())
	}
}

func TestHandlerVehicleDetailResolvesPlateToVIN(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/detail?vin=粤AG18312", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), `"vin":"LB9A32A24R0LS1426"`) {
		t.Fatalf("response should resolve plate to VIN: %s", rec.Body.String())
	}
	var body struct {
		Data VehicleDetail `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.Resolution == nil || !body.Data.Resolution.Resolved || body.Data.Resolution.VIN != "LB9A32A24R0LS1426" {
		t.Fatalf("vehicle detail should include canonical identity resolution, got %+v body=%s", body.Data.Resolution, rec.Body.String())
	}
	if len(body.Data.Resolution.Protocols) < 2 {
		t.Fatalf("vehicle detail resolution should include source protocols, got %+v", body.Data.Resolution.Protocols)
	}
}

func TestHandlerVehicleDetailAcceptsKeyword(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/detail?keyword=粤AG18312", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), `"vin":"LB9A32A24R0LS1426"`) {
		t.Fatalf("response should resolve keyword to VIN: %s", rec.Body.String())
	}
}

func TestHandlerVehicleDetailKeepsUnresolvedLookupOutOfVIN(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/detail?keyword=64646848247", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	for _, want := range []string{`"lookupKey":"64646848247"`, `"lookupResolved":false`, `"vin":""`} {
		if !strings.Contains(rec.Body.String(), want) {
			t.Fatalf("response missing %q: %s", want, rec.Body.String())
		}
	}
	var body struct {
		Data VehicleDetail `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.VIN == "64646848247" {
		t.Fatalf("unresolved lookup should not be returned as top-level VIN: %s", rec.Body.String())
	}
	if len(body.Data.Sources) != 0 || len(body.Data.SourceStatus) != 0 || len(body.Data.Raw.Items) != 0 || len(body.Data.History.Items) != 0 || len(body.Data.Mileage.Items) != 0 {
		t.Fatalf("unresolved lookup should not return vehicle data sections: %+v", body.Data)
	}
}

func TestHandlerVehicleResolveReturnsCanonicalIdentity(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/resolve?keyword=粤AG18312", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleIdentityResolution `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if !body.Data.Resolved || body.Data.VIN != "LB9A32A24R0LS1426" || body.Data.Plate != "粤AG18312" {
		t.Fatalf("resolve should return canonical identity, got %+v body=%s", body.Data, rec.Body.String())
	}
	if len(body.Data.Protocols) < 2 {
		t.Fatalf("resolve should include available source protocols, got %+v", body.Data.Protocols)
	}
	if body.Data.ServiceStatus == nil || body.Data.ServiceStatus.Status != "degraded" {
		t.Fatalf("resolve should include canonical service status, got %+v body=%s", body.Data.ServiceStatus, rec.Body.String())
	}
}

func TestHandlerVehicleResolveKeepsUnresolvedKeyword(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/vehicles/resolve?keyword=64646848247", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data VehicleIdentityResolution `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.Resolved || body.Data.VIN != "" || body.Data.LookupKey != "64646848247" {
		t.Fatalf("unresolved keyword should not fabricate identity, got %+v body=%s", body.Data, rec.Body.String())
	}
}

func TestHandlerRealtimeLocations(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/realtime/locations?limit=10", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
		t.Fatalf("response missing vehicle: %s", rec.Body.String())
	}
}

func TestHandlerVehicleRealtime(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/realtime/vehicles?limit=10", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	for _, want := range []string{"protocols", "sourceCount", "primaryProtocol", "LB9A32A24R0LS1426"} {
		if !strings.Contains(rec.Body.String(), want) {
			t.Fatalf("response missing %q: %s", want, rec.Body.String())
		}
	}
	var body struct {
		Data struct {
			Items []VehicleRealtimeRow `json:"items"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if len(body.Data.Items) == 0 || body.Data.Items[0].ServiceStatus == nil {
		t.Fatalf("realtime vehicle row should include canonical serviceStatus: %s", rec.Body.String())
	}
	byProtocol := map[string]VehicleSourceStatus{}
	for _, source := range body.Data.Items[0].SourceStatus {
		byProtocol[source.Protocol] = source
	}
	for _, protocol := range []string{"GB32960", "JT808", "YUTONG_MQTT"} {
		if _, ok := byProtocol[protocol]; !ok {
			t.Fatalf("realtime row should expose canonical source slot %s, got %+v body=%s", protocol, body.Data.Items[0].SourceStatus, rec.Body.String())
		}
	}
	if !byProtocol["JT808"].Online || byProtocol["YUTONG_MQTT"].Online || byProtocol["YUTONG_MQTT"].HasRealtime {
		t.Fatalf("realtime source slots should expose online and missing evidence, got %+v", byProtocol)
	}
}

func TestHandlerMonitorWorkspaceReturnsCoherentPayload(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/v2/monitor/workspace?zoom=13&railLimit=2", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data MonitorWorkspaceResponse `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.Summary.TotalVehicles == 0 || body.Data.Map.Total == 0 || len(body.Data.Vehicles.Items) != 2 {
		t.Fatalf("workspace response is incomplete: %+v body=%s", body.Data, rec.Body.String())
	}
}

func TestHandlerVehicleRealtimeFiltersServiceStatus(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/realtime/vehicles?serviceStatus=degraded&limit=10", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
		t.Fatalf("degraded realtime should include partially online vehicle: %s", rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "LNXNEGRR7SR318212") {
		t.Fatalf("degraded realtime should include online single-source vehicle that misses canonical sources: %s", rec.Body.String())
	}
}

func TestHandlerVehicleRealtimeKeepsBoundVehiclesWithoutLocation(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/realtime/vehicles?status=no_location&limit=10", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data struct {
			Items []VehicleRealtimeRow `json:"items"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if len(body.Data.Items) == 0 {
		t.Fatalf("no-location filter should retain bound vehicles: %s", rec.Body.String())
	}
	for _, item := range body.Data.Items {
		if item.LocationAvailable {
			t.Fatalf("no-location result must not contain a located vehicle: %+v", item)
		}
	}
}

func TestHandlerVehicleRealtimeOfflineFilterExcludesNeverReportedVehicles(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/realtime/vehicles?online=offline&limit=10", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data struct {
			Items []VehicleRealtimeRow `json:"items"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	for _, item := range body.Data.Items {
		if item.SourceCount == 0 {
			t.Fatalf("offline means a known source stopped reporting; never-reported vehicles belong to no-location: %+v", item)
		}
	}
}

func TestHandlerVehicleRealtimeAcceptsKeyword(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/realtime/vehicles?keyword=川AHTWO1&limit=10", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data struct {
			Items []VehicleRealtimeRow `json:"items"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if len(body.Data.Items) != 1 || body.Data.Items[0].VIN != "LNXNEGRR7SR318212" {
		t.Fatalf("realtime vehicles should accept vehicle keyword, got %+v body=%s", body.Data.Items, rec.Body.String())
	}
}

func TestHandlerVehicleRealtimeAcceptsBatchKeywords(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/realtime/vehicles?keywords=%E7%B2%A4AG18312%2C%E5%B7%9DAHTWO1%2C%E7%B2%A4AG18312&limit=10", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data struct {
			Items []VehicleRealtimeRow `json:"items"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if len(body.Data.Items) != 2 {
		t.Fatalf("batch search should return two deduplicated vehicles, got %+v body=%s", body.Data.Items, rec.Body.String())
	}
}

func TestHandlerVehicleRealtimeBatchKeywordsAreExact(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/realtime/vehicles?keywords=%E7%B2%A4AG1831&limit=10", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data struct {
			Items []VehicleRealtimeRow `json:"items"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if len(body.Data.Items) != 0 {
		t.Fatalf("copied batch plates must not fuzzy-match similar identities, got %+v body=%s", body.Data.Items, rec.Body.String())
	}
}

func TestHandlerHistoryMileageQualityOps(t *testing.T) {
	cases := []struct {
		path string
		want string
	}{
		{"/api/history/locations?limit=10", "totalMileageKm"},
		{"/api/history/raw-frames?protocol=GB32960&vin=LB9A32A24R0LS1426&limit=1&includeFields=true", "plate"},
		{"/api/mileage/summary?limit=10", "totalMileageKm"},
		{"/api/mileage/daily?limit=10", "dailyMileageKm"},
		{"/api/v2/statistics/mileage?dateFrom=2026-07-01&dateTo=2026-07-31", "periodMileageKm"},
		{"/api/statistics/online-summary?limit=10", "onlineRatePercent"},
		{"/api/statistics/online-vehicles?limit=10", "offlineDurationMinutes"},
		{"/api/quality/summary?limit=10", "issueVehicleCount"},
		{"/api/quality/issues?limit=10", "sourceEndpoint"},
		{"/api/alert-events/summary?limit=10", "issueVehicleCount"},
		{"/api/alert-events?limit=10", "sourceEndpoint"},
		{"/api/alert-events/notification-plan?limit=10", "priorityIssues"},
		{"/api/ops/health", "linkHealth"},
	}
	handler := NewHandler(NewService(NewMockStore()))
	for _, tc := range cases {
		t.Run(tc.path, func(t *testing.T) {
			rec := httptest.NewRecorder()
			req := httptest.NewRequest(http.MethodGet, tc.path, nil)
			handler.ServeHTTP(rec, req)
			if rec.Code != http.StatusOK {
				t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
			}
			if !strings.Contains(rec.Body.String(), tc.want) {
				t.Fatalf("response missing %q: %s", tc.want, rec.Body.String())
			}
		})
	}
}

func TestHandlerQualityIncludesNoSourceVehicles(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/quality/issues?limit=20", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data Page[QualityIssueRow] `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	found := false
	for _, item := range body.Data.Items {
		if item.IssueType == "NO_SOURCE" {
			found = true
			if item.VIN == "" || item.Plate == "" || item.Protocol != "VEHICLE_SERVICE" {
				t.Fatalf("NO_SOURCE issue should identify bound vehicle service, got %+v", item)
			}
		}
	}
	if !found {
		t.Fatalf("quality issues should include NO_SOURCE vehicles, got %+v", body.Data.Items)
	}
}

func TestHandlerQualitySummaryIncludesNoSourceBucket(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/quality/summary?limit=20", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data QualitySummary `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	found := false
	for _, item := range body.Data.IssueTypes {
		if item.Name == "NO_SOURCE" {
			found = true
		}
	}
	if !found {
		t.Fatalf("quality summary should include NO_SOURCE bucket, got %+v", body.Data.IssueTypes)
	}
}

func TestBuildQualityIssueWhereUsesMatchingArgs(t *testing.T) {
	fromSQL, args := buildQualityIssueWhere(url.Values{"vin": {"VIN001"}, "protocol": {"VEHICLE_SERVICE"}, "keyword": {"粤A"}})
	if strings.Count(fromSQL, "?") != len(args) {
		t.Fatalf("quality issue SQL placeholders should match args: placeholders=%d args=%d sql=%s args=%#v", strings.Count(fromSQL, "?"), len(args), fromSQL, args)
	}
}

func TestBuildQualityIssueWhereFiltersIssueType(t *testing.T) {
	fromSQL, args := buildQualityIssueWhere(url.Values{"issueType": {"NO_SOURCE"}})
	if !strings.Contains(fromSQL, "q.issue_type = ?") {
		t.Fatalf("quality issue SQL should filter issue type: %s", fromSQL)
	}
	if len(args) != 1 || args[0] != "NO_SOURCE" {
		t.Fatalf("args = %#v", args)
	}
}

func TestHandlerQualityIssuesFiltersIssueType(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/quality/issues?issueType=NO_SOURCE&limit=20", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data Page[QualityIssueRow] `json:"data"`
	}
	if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.Total == 0 {
		t.Fatalf("expected at least one NO_SOURCE issue")
	}
	for _, item := range body.Data.Items {
		if item.IssueType != "NO_SOURCE" {
			t.Fatalf("expected only NO_SOURCE issues, got %+v", body.Data.Items)
		}
	}
}

func TestHandlerQualityNotificationPlan(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/quality/notification-plan?limit=10", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data QualityNotificationPlan `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.ActiveRuleCount == 0 || body.Data.P0RuleCount == 0 {
		t.Fatalf("notification plan should expose active P0 rules, got %+v", body.Data)
	}
	if len(body.Data.Rules) == 0 || len(body.Data.Policies) == 0 || len(body.Data.PriorityIssues) == 0 {
		t.Fatalf("notification plan should include rules, policies and priority issues: %+v", body.Data)
	}
	firstPolicy := body.Data.Policies[0]
	if firstPolicy.EscalationMinutes <= 0 || firstPolicy.AcceptanceCriteria == "" {
		t.Fatalf("notification policies should expose escalation minutes and acceptance criteria: %+v", firstPolicy)
	}
	first := body.Data.PriorityIssues[0]
	if first.Priority != "P0" || first.ActionLabel == "" || first.SLA == "" || first.VehicleLabel == "" {
		t.Fatalf("priority issue should be enriched for notification: %+v", first)
	}
	if !strings.Contains(first.NotificationText, "实时定位") || !strings.Contains(first.NotificationText, "#/history") {
		t.Fatalf("priority issue should include evidence links, got %q", first.NotificationText)
	}
}

func TestHandlerOpsHealthIncludesVehicleServiceRuntime(t *testing.T) {
	handler := NewHandler(NewServiceWithRuntime(NewMockStore(), RuntimeInfo{
		RequestTimeoutMs:         1500,
		AMapWebJSConfigured:      true,
		AMapAPIConfigured:        true,
		AMapSecurityProxyEnabled: true,
		AMapSecurityCodeExposed:  false,
		AMapSecurityServiceHost:  "/_AMapService",
		PlatformRelease:          "platform-20260704153005",
	}))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/ops/health", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data OpsHealth `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.Runtime.RequestTimeoutMs != 1500 {
		t.Fatalf("ops health should include request timeout runtime, got %+v body=%s", body.Data.Runtime, rec.Body.String())
	}
	if !body.Data.Runtime.AMapWebJSConfigured || !body.Data.Runtime.AMapSecurityProxyEnabled {
		t.Fatalf("ops health should expose AMap runtime readiness, got %+v body=%s", body.Data.Runtime, rec.Body.String())
	}
	if !body.Data.Runtime.AMapAPIConfigured {
		t.Fatalf("ops health should expose server-side AMap API readiness, got %+v body=%s", body.Data.Runtime, rec.Body.String())
	}
	if body.Data.Runtime.AMapSecurityCodeExposed {
		t.Fatalf("ops health should show that AMap security code is not exposed when proxy is enabled: %+v", body.Data.Runtime)
	}
	if body.Data.Runtime.AMapSecurityServiceHost != "/_AMapService" {
		t.Fatalf("ops health should include AMap security service host, got %+v", body.Data.Runtime)
	}
	if body.Data.Runtime.PlatformRelease != "platform-20260704153005" {
		t.Fatalf("ops health should include platform release, got %+v", body.Data.Runtime)
	}
}

func TestHandlerSourceReadiness(t *testing.T) {
	handler := NewHandler(NewServiceWithRuntime(NewMockStore(), RuntimeInfo{PlatformRelease: "platform-source-test"}))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/ops/source-readiness", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data SourceReadinessPlan `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode source readiness: %v body=%s", err, rec.Body.String())
	}
	if body.Data.PlatformRelease != "platform-source-test" {
		t.Fatalf("source readiness should expose runtime release, got %+v", body.Data)
	}
	if body.Data.TotalVehicles != body.Data.BoundVehicles+body.Data.IdentityRequiredVehicles {
		t.Fatalf("source readiness vehicle identity population should reconcile, got %+v", body.Data)
	}
	if len(body.Data.Sources) < len(canonicalVehicleProtocols) {
		t.Fatalf("source readiness should expose canonical protocol slots, got %+v", body.Data.Sources)
	}
	byProtocol := map[string]SourceReadinessRow{}
	for _, source := range body.Data.Sources {
		byProtocol[source.Protocol] = source
	}
	for _, protocol := range canonicalVehicleProtocols {
		row, ok := byProtocol[protocol]
		if !ok {
			t.Fatalf("source readiness missing protocol %s: %+v", protocol, body.Data.Sources)
		}
		if row.Role == "" || row.Evidence == "" || row.Action == "" || row.Acceptance == "" {
			t.Fatalf("source readiness row should be operationally actionable: %+v", row)
		}
		if !strings.Contains(row.VehiclesHash, "missingProtocol="+protocol) || !strings.Contains(row.RealtimeHash, "protocol="+protocol) {
			t.Fatalf("source readiness should include workflow hashes, got %+v", row)
		}
	}
}

func TestHandlerVehicleDataAPIsResolveVehicleKeyword(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	cases := []struct {
		name    string
		path    string
		wantVIN string
	}{
		{name: "history locations vin alias", path: "/api/history/locations?vin=粤AG18312&limit=10", wantVIN: "LB9A32A24R0LS1426"},
		{name: "raw frames vin alias", path: "/api/history/raw-frames?vin=粤AG18312&limit=1", wantVIN: "LB9A32A24R0LS1426"},
		{name: "daily mileage vin alias", path: "/api/mileage/daily?vin=粤AG18312&limit=10", wantVIN: "LB9A32A24R0LS1426"},
		{name: "history locations keyword", path: "/api/history/locations?keyword=川AHTWO1&limit=10", wantVIN: "LNXNEGRR7SR318212"},
		{name: "raw frames keyword", path: "/api/history/raw-frames?keyword=川AHTWO1&limit=1", wantVIN: "LNXNEGRR7SR318212"},
		{name: "daily mileage keyword", path: "/api/mileage/daily?keyword=川AHTWO1&limit=10", wantVIN: "LNXNEGRR7SR318212"},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			rec := httptest.NewRecorder()
			req := httptest.NewRequest(http.MethodGet, tc.path, nil)
			handler.ServeHTTP(rec, req)
			if rec.Code != http.StatusOK {
				t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
			}
			var body struct {
				Data struct {
					Items []struct {
						VIN string `json:"vin"`
					} `json:"items"`
				} `json:"data"`
			}
			if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
				t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
			}
			if len(body.Data.Items) == 0 {
				t.Fatalf("vehicle data API should return rows for resolved keyword: %s", rec.Body.String())
			}
			if body.Data.Items[0].VIN != tc.wantVIN {
				t.Fatalf("vehicle data API should resolve keyword to VIN %s, got %s body=%s", tc.wantVIN, body.Data.Items[0].VIN, rec.Body.String())
			}
		})
	}
}

func TestHandlerRawFramesPostAcceptsKeyword(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodPost, "/api/history/raw-frames/query", strings.NewReader(`{"keyword":"川AHTWO1","limit":1}`))
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data struct {
			Items []RawFrameRow `json:"items"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if len(body.Data.Items) != 1 || body.Data.Items[0].VIN != "LNXNEGRR7SR318212" {
		t.Fatalf("raw POST should resolve keyword to VIN, got %+v body=%s", body.Data.Items, rec.Body.String())
	}
}

func TestHandlerRawFramesRejectsUnscopedIncludeFields(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	cases := []struct {
		name string
		req  *http.Request
	}{
		{
			name: "get",
			req:  httptest.NewRequest(http.MethodGet, "/api/history/raw-frames?limit=1&includeFields=true", nil),
		},
		{
			name: "post",
			req:  httptest.NewRequest(http.MethodPost, "/api/history/raw-frames/query", strings.NewReader(`{"limit":1,"includeFields":true}`)),
		},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			rec := httptest.NewRecorder()
			handler.ServeHTTP(rec, tc.req)
			if rec.Code != http.StatusBadRequest {
				t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
			}
			var body struct {
				Error struct {
					Code    string `json:"code"`
					Message string `json:"message"`
				} `json:"error"`
			}
			if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
				t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
			}
			if body.Error.Code != "RAW_FRAME_SCOPE_REQUIRED" {
				t.Fatalf("error code = %q body=%s", body.Error.Code, rec.Body.String())
			}
			if !strings.Contains(body.Error.Message, "车辆或时间范围") {
				t.Fatalf("error message should explain required scope: %s", rec.Body.String())
			}
		})
	}
}

func TestHandlerRawFramesKeepsUnresolvedKeywordEmpty(t *testing.T) {
	handler := NewHandler(NewService(NewMockStore()))
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/history/raw-frames?keyword=64646848247&limit=1", nil)
	handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
	}
	var body struct {
		Data Page[RawFrameRow] `json:"data"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
	}
	if body.Data.Total != 0 || len(body.Data.Items) != 0 {
		t.Fatalf("unresolved keyword should not fabricate raw rows: %+v body=%s", body.Data, rec.Body.String())
	}
}
