"""
建立 system_functions 資料表
"""
import psycopg2

conn = psycopg2.connect(
    host="10.1.0.20",
    port=5433,
    database="hr_portal",
    user="admin",
    password="DC1qaz2wsx"
)
conn.autocommit = False
cur = conn.cursor()

try:
    print("Creating system_functions table...")

    # 建立資料表
    cur.execute("""
        CREATE TABLE IF NOT EXISTS system_functions (
            id INTEGER PRIMARY KEY,
            code VARCHAR(200) NOT NULL,
            upper_function_id INTEGER NOT NULL DEFAULT 0,
            name VARCHAR(200) NOT NULL,
            function_type INTEGER NOT NULL,
            "order" INTEGER NOT NULL,
            function_icon VARCHAR(200) NOT NULL DEFAULT '',
            module_code VARCHAR(200),
            module_functions JSON NOT NULL DEFAULT '[]',
            description TEXT NOT NULL DEFAULT '',
            is_mana BOOLEAN NOT NULL DEFAULT true,
            is_active BOOLEAN NOT NULL DEFAULT true,
            edit_by INTEGER NOT NULL,
            created_at TIMESTAMP NOT NULL DEFAULT NOW(),
            updated_at TIMESTAMP
        );
    """)

    # 建立索引
    cur.execute("CREATE INDEX IF NOT EXISTS ix_system_functions_code ON system_functions(code);")
    cur.execute("CREATE INDEX IF NOT EXISTS ix_system_functions_upper_function_id ON system_functions(upper_function_id);")
    cur.execute("CREATE INDEX IF NOT EXISTS ix_system_functions_function_type ON system_functions(function_type);")
    cur.execute("CREATE INDEX IF NOT EXISTS ix_system_functions_is_active ON system_functions(is_active);")

    # 建立序列 (從 10 開始)
    cur.execute("""
        CREATE SEQUENCE IF NOT EXISTS system_functions_id_seq
        START WITH 10
        INCREMENT BY 1
        MINVALUE 10
        NO MAXVALUE
        CACHE 1;
    """)

    # 設定 id 欄位使用序列
    cur.execute("""
        ALTER TABLE system_functions
        ALTER COLUMN id SET DEFAULT nextval('system_functions_id_seq');
    """)

    # 將序列所有權給予資料表
    cur.execute("""
        ALTER SEQUENCE system_functions_id_seq
        OWNED BY system_functions.id;
    """)

    conn.commit()
    print("[OK] system_functions table created successfully")

except Exception as e:
    conn.rollback()
    print(f"ERROR: {e}")
    import traceback
    traceback.print_exc()
finally:
    cur.close()
    conn.close()
