"""
修正租戶的 code 為小寫
"""
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("Updating tenants.code to lowercase...")

    # 更新為小寫
    cur.execute("""
        UPDATE tenants
        SET code = LOWER(code)
        WHERE id = 1;
    """)

    conn.commit()
    print("SUCCESS: tenants.code updated to lowercase")

    # 驗證
    cur.execute("SELECT id, code, keycloak_realm FROM tenants WHERE id = 1;")
    result = cur.fetchone()
    if result:
        print(f"\nVerified:")
        print(f"  ID: {result[0]}")
        print(f"  Code: {result[1]}")
        print(f"  Keycloak Realm: {result[2]}")
        print(f"\n✅ Both fields are now lowercase!")

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