package com.lingniu.ingest.tdenginehistory;

import org.junit.jupiter.api.Test;

import java.nio.file.Files;
import java.nio.file.Path;

import static org.assertj.core.api.Assertions.assertThat;

class TdengineHistorySchemaTest {

    @Test
    void bootstrapSqlCreatesOnlyRawAndLocationStablesFromSpec() {
        TdengineHistorySchema schema = new TdengineHistorySchema("vehicle_history");

        assertThat(schema.bootstrapSql())
                .first()
                .isEqualTo("CREATE DATABASE IF NOT EXISTS vehicle_history PRECISION 'ms'");
        assertThat(schema.bootstrapSql())
                .contains("USE vehicle_history");
        assertThat(schema.bootstrapSql().get(2))
                .contains("CREATE STABLE IF NOT EXISTS raw_frames")
                .contains("frame_id NCHAR(64)")
                .contains("raw_uri NCHAR(512)")
                .contains("metadata_json NCHAR(4096)")
                .contains("parsed_json VARCHAR(16374)")
                .contains("TAGS (")
                .contains("protocol NCHAR(16)")
                .contains("vehicle_key NCHAR(128)")
                .contains("phone NCHAR(32)");
        assertThat(schema.bootstrapSql().get(3))
                .contains("CREATE STABLE IF NOT EXISTS vehicle_locations")
                .contains("longitude DOUBLE")
                .contains("total_mileage_km DOUBLE")
                .contains("raw_uri NCHAR(512)");
        assertThat(schema.bootstrapSql()).hasSize(4);
        assertThat(String.join("\n", schema.bootstrapSql()))
                .doesNotContain("telemetry_fields")
                .doesNotContain("field_key");
    }

    @Test
    void childTableNamesAreStableAndSanitized() {
        TdengineHistorySchema schema = new TdengineHistorySchema("vehicle_history");

        assertThat(schema.rawFrameTable("JT808", "jt808:g7gps/013800000000"))
                .matches("raw_jt808_[0-9a-f]{16}");
        assertThat(schema.locationTable("GB32960", "VIN WITH SPACE"))
                .matches("loc_gb32960_[0-9a-f]{16}");
    }

    @Test
    void historyStorePublicApiDoesNotExposeTelemetryFields() throws Exception {
        String writer = Files.readString(Path.of(
                "src/main/java/com/lingniu/ingest/tdenginehistory/TdengineHistoryWriter.java"));
        String reader = Files.readString(Path.of(
                "src/main/java/com/lingniu/ingest/tdenginehistory/TdengineHistoryReader.java"));

        assertThat(writer)
                .doesNotContain("TelemetryField")
                .doesNotContain("appendTelemetry");
        assertThat(reader)
                .doesNotContain("TelemetryField")
                .doesNotContain("queryTelemetry");
    }
}
