package com.lingniu.ingest.tdenginehistory;

import java.time.Instant;

public record TdengineRawFrameQuery(
        String protocol,
        String vehicleKey,
        String vin,
        String phone,
        Integer messageId,
        String parseStatus,
        Instant from,
        Instant to,
        TdengineQueryOrder order,
        int limit,
        TdenginePageCursor cursor
) {
    public TdengineRawFrameQuery(String protocol,
                                 String vehicleKey,
                                 Instant from,
                                 Instant to,
                                 TdengineQueryOrder order,
                                 int limit,
                                 TdenginePageCursor cursor) {
        this(protocol, vehicleKey, "", "", null, "", from, to, order, limit, cursor);
    }

    public TdengineRawFrameQuery {
        if (protocol == null || protocol.isBlank()) {
            throw new IllegalArgumentException("protocol must not be blank");
        }
        if (from == null || to == null || !from.isBefore(to)) {
            throw new IllegalArgumentException("query time range must be valid");
        }
        protocol = protocol.trim().toUpperCase();
        vehicleKey = trim(vehicleKey);
        vin = trim(vin);
        phone = trim(phone);
        parseStatus = trim(parseStatus);
        order = order == null ? TdengineQueryOrder.DESC : order;
        limit = Math.max(1, Math.min(limit, 1001));
    }

    TdengineRawFrameQuery withLimit(int newLimit) {
        return new TdengineRawFrameQuery(protocol, vehicleKey, vin, phone, messageId, parseStatus,
                from, to, order, newLimit, cursor);
    }

    boolean childTableQuery() {
        return !vehicleKey.isBlank()
                && vin.isBlank()
                && phone.isBlank()
                && messageId == null
                && parseStatus.isBlank();
    }

    private static String trim(String value) {
        return value == null ? "" : value.trim();
    }
}
