package platform

import (
	"strings"
	"testing"
)

func TestReconciliationSQLUsesCollationSafeCrossTableKeys(t *testing.T) {
	checks := map[string][]string{
		"coverage": {
			"BINARY b.vin=BINARY s.vin",
			"BINARY s.vin=BINARY b.vin",
		},
		"position": {
			"BINARY b.vin=BINARY a.vin",
			"BINARY binding.vin=BINARY a.vin",
		},
		"mileage": {
			"BINARY b.vin=BINARY m.vin",
		},
		"fleet count": {
			"SELECT CAST(vin AS BINARY) vin FROM vehicle_identity_binding",
			"UNION SELECT CAST(vin AS BINARY) vin FROM vehicle_realtime_snapshot",
			"BINARY b.vin=BINARY s.vin",
		},
		"business scope": {
			"BINARY s.source_version=BINARY st.active_version",
			"BINARY b.vin=BINARY s.vin",
			"BINARY CAST(s.customer_id AS CHAR)=BINARY u.customer_ref",
			"BINARY s.vin=BINARY g.vin",
			"BINARY b.vin=BINARY g.vin",
			"CONVERT(s.vin USING utf8mb4) COLLATE utf8mb4_unicode_ci",
			"CONVERT(g.vin USING utf8mb4) COLLATE utf8mb4_unicode_ci",
			"CONVERT(COALESCE(b.plate,'') USING utf8mb4) COLLATE utf8mb4_unicode_ci",
		},
	}
	sqlByName := map[string]string{
		"coverage":       reconciliationCoverageSQL,
		"position":       reconciliationPositionSQL,
		"mileage":        reconciliationMileageSQL,
		"fleet count":    reconciliationFleetCountSQL,
		"business scope": reconciliationBusinessScopeSQL,
	}
	for name, fragments := range checks {
		for _, fragment := range fragments {
			if !strings.Contains(sqlByName[name], fragment) {
				t.Errorf("%s reconciliation SQL is missing %q", name, fragment)
			}
		}
	}
}

func TestReconciliationTrendSQLSupportsOnlyFullGroupBy(t *testing.T) {
	if !strings.Contains(reconciliationTrendSQL, "DATE_FORMAT(MIN(finished_at),'%Y-%m-%d')") {
		t.Fatalf("trend date must be derived from an aggregate: %s", reconciliationTrendSQL)
	}
	if strings.Contains(reconciliationTrendSQL, "SELECT DATE_FORMAT(DATE(finished_at)") {
		t.Fatalf("trend query must not select a non-aggregated finished_at expression: %s", reconciliationTrendSQL)
	}
}
