"""Migrate notification_settings table for FCM push notifications"""
import mysql.connector

DB_CONFIG = {
    'host': 'officialsite.kr',
    'port': 23306,
    'user': 'admin',
    'password': 'dlgks~123',
    'database': 'freeflow',
}

def get_columns(cursor, table):
    cursor.execute(f"SHOW COLUMNS FROM {table}")
    return {row[0] for row in cursor.fetchall()}

def main():
    conn = mysql.connector.connect(**DB_CONFIG)
    cursor = conn.cursor()
    
    existing = get_columns(cursor, 'notification_settings')
    print(f"Existing columns: {existing}")
    
    # Add new columns
    add_columns = {
        'email_enabled': "TINYINT(1) NOT NULL DEFAULT 1",
        'push_enabled': "TINYINT(1) NOT NULL DEFAULT 0",
        'sms_enabled': "TINYINT(1) NOT NULL DEFAULT 0",
        'document_alerts': "TINYINT(1) NOT NULL DEFAULT 1",
        'tax_alerts': "TINYINT(1) NOT NULL DEFAULT 1",
        'fcm_token': "VARCHAR(500) NULL",
        'fcm_token_updated_at': "DATETIME NULL",
    }
    
    for col, definition in add_columns.items():
        if col not in existing:
            q = f"ALTER TABLE notification_settings ADD COLUMN {col} {definition}"
            try:
                cursor.execute(q)
                print(f"OK: Added {col}")
            except Exception as e:
                print(f"SKIP: {e}")
        else:
            print(f"SKIP: {col} already exists")
    
    # Drop old columns that no longer exist in schema
    drop_columns = ['payment_reminders', 'document_updates']
    for col in drop_columns:
        if col in existing:
            q = f"ALTER TABLE notification_settings DROP COLUMN {col}"
            try:
                cursor.execute(q)
                print(f"OK: Dropped {col}")
            except Exception as e:
                print(f"SKIP: {e}")
        else:
            print(f"SKIP: {col} does not exist")
    
    conn.commit()
    cursor.close()
    conn.close()
    print("\nMigration complete.")

if __name__ == '__main__':
    main()
