package com.lingniu.ingest.tdenginehistory;

import java.util.List;

/**
 * SQL model for the TDengine hot history store.
 */
public final class TdengineHistorySchema {

    private final String database;

    public TdengineHistorySchema(String database) {
        this.database = TdengineIdentifier.database(database);
    }

    public List<String> bootstrapSql() {
        return List.of(
                "CREATE DATABASE IF NOT EXISTS " + database + " PRECISION 'ms'",
                "USE " + database,
                rawFramesStableSql(),
                vehicleLocationsStableSql()
        );
    }

    public String rawFrameTable(String protocol, String vehicleKey) {
        return "raw_" + TdengineIdentifier.fragment(protocol) + "_" + TdengineIdentifier.hash16(vehicleKey);
    }

    public String rawFramesStableTable() {
        return "raw_frames";
    }

    public String locationsStableTable() {
        return "vehicle_locations";
    }

    public String locationTable(String protocol, String vehicleKey) {
        return "loc_" + TdengineIdentifier.fragment(protocol) + "_" + TdengineIdentifier.hash16(vehicleKey);
    }

    private static String rawFramesStableSql() {
        return """
                CREATE STABLE IF NOT EXISTS raw_frames (
                  ts TIMESTAMP,
                  frame_id NCHAR(64),
                  received_at TIMESTAMP,
                  message_id INT,
                  sub_type INT,
                  event_time TIMESTAMP,
                  raw_uri NCHAR(512),
                  checksum NCHAR(128),
                  raw_size_bytes BIGINT,
                  parse_status NCHAR(16),
                  parse_error NCHAR(512),
                  peer NCHAR(128),
                  metadata_json NCHAR(4096),
                  parsed_json VARCHAR(16374)
                ) TAGS (
                  protocol NCHAR(16),
                  vehicle_key NCHAR(128),
                  vin NCHAR(64),
                  phone NCHAR(32)
                )""";
    }

    private static String vehicleLocationsStableSql() {
        return """
                CREATE STABLE IF NOT EXISTS vehicle_locations (
                  ts TIMESTAMP,
                  fact_id NCHAR(64),
                  frame_id NCHAR(64),
                  received_at TIMESTAMP,
                  longitude DOUBLE,
                  latitude DOUBLE,
                  altitude_m DOUBLE,
                  speed_kmh DOUBLE,
                  direction_deg DOUBLE,
                  alarm_flag BIGINT,
                  status_flag BIGINT,
                  total_mileage_km DOUBLE,
                  raw_uri NCHAR(512)
                ) TAGS (
                  protocol NCHAR(16),
                  vehicle_key NCHAR(128),
                  vin NCHAR(64),
                  phone NCHAR(32)
                )""";
    }

}
