-- SQL_Script/init_room_status.sql
-- Room Status 快照表初始化（不包含 CREATE DATABASE）

CREATE SCHEMA IF NOT EXISTS room_status;

CREATE TABLE IF NOT EXISTS room_status.room_status_moment (
    guid UUID NOT NULL,
    ts_ms INT8 NOT NULL DEFAULT (EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000)::BIGINT,
    hotel_id INT2 NOT NULL,
    room_id TEXT NOT NULL,
    device_id TEXT NOT NULL,

    sys_lock_status INT2,
    online_status INT2,
    launcher_version TEXT,
    app_version TEXT,
    config_version TEXT,
    register_ts_ms INT8,
    upgrade_ts_ms INT8,
    config_ts_ms INT8,
    ip TEXT,

    pms_status INT2,
    power_state INT2,
    cardless_state INT2,
    service_mask INT8,
    insert_card INT2,
    bright_g INT2,
    agreement_ver TEXT,

    air_address TEXT[],
    air_state INT2[],
    air_model INT2[],
    air_speed INT2[],
    air_set_temp INT2[],
    air_now_temp INT2[],
    air_solenoid_valve INT2[],

    elec_address TEXT[],
    elec_voltage DOUBLE PRECISION[],
    elec_ampere DOUBLE PRECISION[],
    elec_power DOUBLE PRECISION[],
    elec_phase DOUBLE PRECISION[],
    elec_energy DOUBLE PRECISION[],
    elec_sum_energy DOUBLE PRECISION[],

    carbon_state INT2,
    dev_loops JSONB,
    energy_carbon_sum DOUBLE PRECISION,
    energy_nocard_sum DOUBLE PRECISION,
    external_device JSONB DEFAULT '{}',
    faulty_device_count JSONB DEFAULT '{}',

    PRIMARY KEY (hotel_id, room_id, device_id, guid)
) PARTITION BY LIST (hotel_id);

CREATE INDEX IF NOT EXISTS idx_room_status_moment_hotel_room ON room_status.room_status_moment (hotel_id, room_id);
CREATE INDEX IF NOT EXISTS idx_room_status_moment_device_id ON room_status.room_status_moment (device_id);
CREATE INDEX IF NOT EXISTS idx_room_status_moment_sys_lock ON room_status.room_status_moment (sys_lock_status);
CREATE INDEX IF NOT EXISTS idx_room_status_moment_online ON room_status.room_status_moment (online_status);
CREATE INDEX IF NOT EXISTS idx_room_status_moment_pms ON room_status.room_status_moment (pms_status);
CREATE INDEX IF NOT EXISTS idx_room_status_moment_power ON room_status.room_status_moment (power_state);
CREATE INDEX IF NOT EXISTS idx_room_status_moment_cardless ON room_status.room_status_moment (cardless_state);
CREATE INDEX IF NOT EXISTS idx_room_status_moment_insert_card ON room_status.room_status_moment (insert_card);
CREATE INDEX IF NOT EXISTS idx_room_status_moment_carbon ON room_status.room_status_moment (carbon_state);
CREATE UNIQUE INDEX IF NOT EXISTS idx_room_status_unique_device ON room_status.room_status_moment (hotel_id, room_id, device_id);
