-- SQL_Script/init_rcu_action.sql
-- RCU Action 主业务表初始化（不包含 CREATE DATABASE）

CREATE SCHEMA IF NOT EXISTS rcu_action;

CREATE TABLE IF NOT EXISTS rcu_action.rcu_action_events (
    guid VARCHAR(32) NOT NULL,
    ts_ms BIGINT NOT NULL,
    write_ts_ms BIGINT NOT NULL,
    hotel_id INTEGER NOT NULL,
    room_id VARCHAR(32) NOT NULL,
    device_id VARCHAR(32) NOT NULL,
    direction VARCHAR(10) NOT NULL,
    cmd_word VARCHAR(10) NOT NULL,
    frame_id INTEGER NOT NULL,
    udp_raw TEXT NOT NULL,
    action_type VARCHAR(20) NOT NULL,
    sys_lock_status SMALLINT,
    report_count SMALLINT,
    dev_type SMALLINT,
    dev_addr SMALLINT,
    dev_loop INTEGER,
    dev_data INTEGER,
    fault_count SMALLINT,
    error_type SMALLINT,
    error_data SMALLINT,
    type_l SMALLINT,
    type_h SMALLINT,
    details JSONB,
    extra JSONB,
    loop_name VARCHAR(255),
    PRIMARY KEY (ts_ms, guid)
) PARTITION BY RANGE (ts_ms);

ALTER TABLE rcu_action.rcu_action_events
  ADD COLUMN IF NOT EXISTS device_id VARCHAR(32) NOT NULL DEFAULT '';

ALTER TABLE rcu_action.rcu_action_events
  ADD COLUMN IF NOT EXISTS loop_name VARCHAR(255);

CREATE INDEX IF NOT EXISTS idx_rcu_action_hotel_id ON rcu_action.rcu_action_events (hotel_id);
CREATE INDEX IF NOT EXISTS idx_rcu_action_room_id ON rcu_action.rcu_action_events (room_id);
CREATE INDEX IF NOT EXISTS idx_rcu_action_device_id ON rcu_action.rcu_action_events (device_id);
CREATE INDEX IF NOT EXISTS idx_rcu_action_direction ON rcu_action.rcu_action_events (direction);
CREATE INDEX IF NOT EXISTS idx_rcu_action_cmd_word ON rcu_action.rcu_action_events (cmd_word);
CREATE INDEX IF NOT EXISTS idx_rcu_action_action_type ON rcu_action.rcu_action_events (action_type);
CREATE INDEX IF NOT EXISTS idx_rcu_action_query_main ON rcu_action.rcu_action_events (hotel_id, room_id, ts_ms DESC);
