#!/usr/bin/env python
"""Fix branch_id column type in users table"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection

print("Fixing branch_id column type in users table...")

with connection.cursor() as cursor:
    # First, remove the foreign key constraint if it exists
    cursor.execute("""
        SELECT CONSTRAINT_NAME
        FROM information_schema.KEY_COLUMN_USAGE
        WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = 'users'
        AND COLUMN_NAME = 'branch_id'
        AND REFERENCED_TABLE_NAME IS NOT NULL
    """)
    
    fk_constraint = cursor.fetchone()
    if fk_constraint:
        print(f"Dropping foreign key constraint: {fk_constraint[0]}")
        cursor.execute(f"ALTER TABLE users DROP FOREIGN KEY {fk_constraint[0]}")
    
    # Modify the column type
    print("Changing branch_id column type to CHAR(32)...")
    cursor.execute("""
        ALTER TABLE users
        MODIFY COLUMN branch_id CHAR(32) NULL
    """)
    
    # Re-add the foreign key constraint
    print("Adding foreign key constraint...")
    cursor.execute("""
        ALTER TABLE users
        ADD CONSTRAINT users_branch_id_fk
        FOREIGN KEY (branch_id) REFERENCES users_branch(id)
        ON DELETE SET NULL
    """)
    
    print("✓ branch_id column type fixed successfully!")
