"""
插入 dashboard 系統功能記錄
"""
import psycopg2
from datetime import datetime

# 資料庫連線參數
DB_CONFIG = {
    'host': '10.1.0.20',
    'port': 5433,
    'database': 'hr_portal',
    'user': 'admin',
    'password': 'DC1qaz2wsx'
}

def insert_dashboard_function():
    """插入 dashboard 功能記錄"""
    try:
        conn = psycopg2.connect(**DB_CONFIG)
        cursor = conn.cursor()

        today = datetime.now()

        # 插入 SQL
        insert_sql = """
        INSERT INTO system_functions (
            id,
            code,
            upper_function_id,
            name,
            function_type,
            "order",
            module_code,
            module_functions,
            description,
            is_active,
            edit_by,
            created_at,
            updated_at
        ) VALUES (
            23,
            'dashboard',
            0,
            '系統首頁',
            2,
            10,
            'dashboard',
            '["Create", "Read"]'::jsonb,
            '',
            true,
            1,
            %s,
            %s
        )
        ON CONFLICT (id) DO UPDATE SET
            code = EXCLUDED.code,
            upper_function_id = EXCLUDED.upper_function_id,
            name = EXCLUDED.name,
            function_type = EXCLUDED.function_type,
            "order" = EXCLUDED."order",
            module_code = EXCLUDED.module_code,
            module_functions = EXCLUDED.module_functions,
            description = EXCLUDED.description,
            is_active = EXCLUDED.is_active,
            edit_by = EXCLUDED.edit_by,
            updated_at = EXCLUDED.updated_at;
        """

        cursor.execute(insert_sql, (today, today))
        conn.commit()

        print("[OK] Dashboard 功能記錄插入成功")
        print(f"    ID: 23")
        print(f"    Code: dashboard")
        print(f"    Name: 系統首頁")
        print(f"    Module Functions: [Create, Read]")

        # 驗證插入
        cursor.execute("SELECT id, code, name, module_functions FROM system_functions WHERE id = 23;")
        result = cursor.fetchone()

        if result:
            print(f"\n[Verified] 記錄已確認存在:")
            print(f"    ID: {result[0]}")
            print(f"    Code: {result[1]}")
            print(f"    Name: {result[2]}")
            print(f"    Module Functions: {result[3]}")
        else:
            print("[WARNING] 記錄插入後查詢不到")

        cursor.close()
        conn.close()

    except psycopg2.Error as e:
        print(f"[ERROR] Database error: {e}")
        raise
    except Exception as e:
        print(f"[ERROR] Unexpected error: {e}")
        raise

if __name__ == "__main__":
    insert_dashboard_function()
