"""
fix_rollover_interest_column.py
--------------------------------
The rollover_requests.requested_interest_rate column is DECIMAL(5,2) on the
production server (migration 0002 created it that way). Migration 0031 widened
it to DECIMAL(12,2) but was never run.

This script applies that change directly with ALTER TABLE.

Run on the server: python3 fix_rollover_interest_column.py
"""
import pymysql

DB_HOST     = "localhost"
DB_PORT     = 3306
DB_NAME     = "xygbfpsg_loans"
DB_USER     = "xygbfpsg_graz"
DB_PASSWORD = "j.ez-xy6##y.rllB"

conn = pymysql.connect(
    host=DB_HOST, port=DB_PORT, db=DB_NAME,
    user=DB_USER, password=DB_PASSWORD, charset="utf8mb4",
)

with conn.cursor() as cur:
    # Check current column definition
    cur.execute("""
        SELECT COLUMN_TYPE FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME   = 'rollover_requests'
          AND COLUMN_NAME  = 'requested_interest_rate'
    """)
    row = cur.fetchone()
    if not row:
        print("Column rollover_requests.requested_interest_rate not found — nothing to do.")
        conn.close()
        exit(0)

    current_type = row[0]
    print(f"Current type: {current_type}")

    if 'decimal(12' in current_type.lower():
        print("Already DECIMAL(12,2) — no change needed.")
        conn.close()
        exit(0)

    print("Altering to DECIMAL(12,2) ...")
    cur.execute("""
        ALTER TABLE rollover_requests
        MODIFY COLUMN requested_interest_rate DECIMAL(12,2) NULL
    """)
    conn.commit()

    # Verify
    cur.execute("""
        SELECT COLUMN_TYPE FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME   = 'rollover_requests'
          AND COLUMN_NAME  = 'requested_interest_rate'
    """)
    new_type = cur.fetchone()[0]
    print(f"New type:     {new_type}")
    print("Done ✓")

conn.close()
