package history

const DefaultDatabase = "lingniu_vehicle_ts"

func SchemaStatements(database string) []string {
	if database == "" {
		database = DefaultDatabase
	}
	return []string{
		"CREATE DATABASE IF NOT EXISTS " + database + " KEEP 7300 DURATION 10 BUFFER 256",
		"USE " + database,
		`CREATE STABLE IF NOT EXISTS raw_frames (
  ts TIMESTAMP,
  frame_id NCHAR(64),
  event_id NCHAR(64),
  message_id INT,
  event_time TIMESTAMP,
  received_at TIMESTAMP,
  raw_size_bytes INT,
  raw_hex BINARY(16374),
  raw_text BINARY(16374),
  parsed_json BINARY(16374),
  parse_status NCHAR(16),
  parse_error BINARY(1024),
  source_endpoint NCHAR(128)
) TAGS (
  protocol NCHAR(32),
  vehicle_key NCHAR(64),
  vin NCHAR(32),
  phone NCHAR(32),
  device_id NCHAR(64)
)`,
		`CREATE STABLE IF NOT EXISTS raw_frame_payload_chunks (
  ts TIMESTAMP,
  event_id NCHAR(64),
  frame_id NCHAR(64),
  received_at TIMESTAMP,
  payload_kind NCHAR(32),
  chunk_index INT,
  chunk_count INT,
  chunk_text BINARY(16000)
) TAGS (
  protocol NCHAR(32),
  vehicle_key NCHAR(64),
  vin NCHAR(32),
  phone NCHAR(32),
  device_id NCHAR(64)
)`,
		`CREATE STABLE IF NOT EXISTS vehicle_locations (
  ts TIMESTAMP,
  event_id NCHAR(64),
  received_at TIMESTAMP,
  longitude DOUBLE,
  latitude DOUBLE,
  altitude_m DOUBLE,
  speed_kmh DOUBLE,
  soc_percent DOUBLE,
  direction_deg INT,
  alarm_flag BIGINT,
  status_flag BIGINT,
  total_mileage_km DOUBLE
) TAGS (
  protocol NCHAR(32),
  vin NCHAR(32)
)`,
	}
}

// SchemaMigrationStatements contains additive TDengine changes that must also
// be applied to an already existing stable. The writer treats duplicate-column
// errors as success so startup remains idempotent across releases.
func SchemaMigrationStatements(database string) []string {
	if database == "" {
		database = DefaultDatabase
	}
	return []string{"ALTER STABLE " + database + ".vehicle_locations ADD COLUMN soc_percent DOUBLE"}
}
