-- 创建流量使用记录表
CREATE TABLE IF NOT EXISTS tb_data_usage_record (
    id SERIAL PRIMARY KEY,
    iot_card_id INTEGER NOT NULL,
    data_usage_mb BIGINT NOT NULL DEFAULT 0,
    data_increase_mb BIGINT DEFAULT 0,
    check_time TIMESTAMP NOT NULL,
    source VARCHAR(50) DEFAULT 'polling',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT fk_data_usage_record_iot_card FOREIGN KEY (iot_card_id) REFERENCES tb_iot_card(id) ON DELETE CASCADE
);

-- 创建索引
CREATE INDEX IF NOT EXISTS idx_data_usage_record_iot_card_id ON tb_data_usage_record(iot_card_id);
CREATE INDEX IF NOT EXISTS idx_data_usage_record_check_time ON tb_data_usage_record(check_time);
CREATE INDEX IF NOT EXISTS idx_data_usage_record_iot_card_check_time ON tb_data_usage_record(iot_card_id, check_time DESC);

COMMENT ON TABLE tb_data_usage_record IS '流量使用记录表';
COMMENT ON COLUMN tb_data_usage_record.id IS '流量使用记录ID';
COMMENT ON COLUMN tb_data_usage_record.iot_card_id IS 'IoT卡ID';
COMMENT ON COLUMN tb_data_usage_record.data_usage_mb IS '流量使用量(MB)';
COMMENT ON COLUMN tb_data_usage_record.data_increase_mb IS '相比上次的增量(MB)';
COMMENT ON COLUMN tb_data_usage_record.check_time IS '检查时间';
COMMENT ON COLUMN tb_data_usage_record.source IS '数据来源 polling-轮询 manual-手动 gateway-回调';
COMMENT ON COLUMN tb_data_usage_record.created_at IS '创建时间';
