# Generated by Django - Cleanup orphaned notification table
# This migration addresses IntegrityError caused by orphaned foreign key constraints
# from a previous version of the plugin that included a notification table

from django.db import migrations


def cleanup_orphaned_notification_table(apps, schema_editor):
    """
    Clean up orphaned notification table that causes IntegrityError.
    
    This function safely removes the orphaned netbox_maintenance_device_maintenancenotification
    table and its constraints that prevent MaintenancePlan operations.
    """
    from django.db import connection
    import logging
    
    logger = logging.getLogger('netbox_maintenance_device')
    
    # Skip cleanup during collectstatic or other operations that don't need database access
    if connection.settings_dict.get('NAME') == ':memory:':
        logger.info("NetBox Maintenance Device: Skipping cleanup for in-memory database")
        return
    
    try:
        with connection.cursor() as cursor:
            # Check if we're using PostgreSQL, SQLite, or another database
            cursor.execute("SELECT version();")
            db_version = cursor.fetchone()[0]
            is_postgresql = 'PostgreSQL' in db_version
            is_sqlite = 'SQLite' in db_version
            
            # Check if the orphaned notification table exists
            table_exists = False
            
            if is_postgresql:
                cursor.execute("""
                    SELECT EXISTS (
                        SELECT 1 FROM information_schema.tables 
                        WHERE table_schema = 'public'
                        AND table_name = 'netbox_maintenance_device_maintenancenotification'
                    );
                """)
                result = cursor.fetchone()
                table_exists = result[0] if result else False
                
            elif is_sqlite:
                cursor.execute("""
                    SELECT name FROM sqlite_master 
                    WHERE type='table' 
                    AND name='netbox_maintenance_device_maintenancenotification';
                """)
                result = cursor.fetchone()
                table_exists = bool(result)
                
            else:
                # Try generic approach for other databases
                try:
                    cursor.execute("SELECT 1 FROM netbox_maintenance_device_maintenancenotification LIMIT 1;")
                    table_exists = True
                except:
                    table_exists = False
            
            if table_exists:
                logger.warning("NetBox Maintenance Device: Found orphaned notification table, cleaning up...")
                
                # Get information about existing records (for logging)
                try:
                    cursor.execute("SELECT COUNT(*) FROM netbox_maintenance_device_maintenancenotification;")
                    record_count = cursor.fetchone()[0]
                    logger.info(f"NetBox Maintenance Device: Removing {record_count} orphaned notification records")
                except:
                    record_count = 0
                
                # Remove all records first to clear foreign key dependencies
                cursor.execute("DELETE FROM netbox_maintenance_device_maintenancenotification;")
                
                # Drop foreign key constraints (PostgreSQL specific)
                if is_postgresql:
                    try:
                        # Get constraint names
                        cursor.execute("""
                            SELECT constraint_name 
                            FROM information_schema.table_constraints 
                            WHERE table_name = 'netbox_maintenance_device_maintenancenotification'
                            AND constraint_type = 'FOREIGN KEY';
                        """)
                        
                        constraints = cursor.fetchall()
                        for constraint_row in constraints:
                            constraint_name = constraint_row[0]
                            try:
                                cursor.execute(f"""
                                    ALTER TABLE netbox_maintenance_device_maintenancenotification 
                                    DROP CONSTRAINT IF EXISTS "{constraint_name}";
                                """)
                                logger.debug(f"NetBox Maintenance Device: Dropped constraint {constraint_name}")
                            except Exception as e:
                                logger.warning(f"NetBox Maintenance Device: Could not drop constraint {constraint_name}: {e}")
                    except Exception as e:
                        logger.warning(f"NetBox Maintenance Device: Could not query constraints: {e}")
                
                # Finally, drop the entire orphaned table
                cursor.execute("DROP TABLE IF EXISTS netbox_maintenance_device_maintenancenotification;")
                logger.info("NetBox Maintenance Device: Successfully removed orphaned notification table")
                
            else:
                logger.debug("NetBox Maintenance Device: No orphaned notification table found - database is clean")
                
    except Exception as e:
        # Log the error but don't fail the migration
        logger.warning(f"NetBox Maintenance Device: Warning during cleanup: {e}")
        # Continue with migration - this cleanup is best-effort


def reverse_cleanup(apps, schema_editor):
    """
    This migration is irreversible as we're cleaning up orphaned data.
    The notification table was not part of the current plugin design.
    """
    import logging
    logger = logging.getLogger('netbox_maintenance_device')
    logger.info("NetBox Maintenance Device: Cannot reverse orphaned table cleanup - migration is irreversible")


class Migration(migrations.Migration):

    dependencies = [
        ('netbox_maintenance_device', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(
            cleanup_orphaned_notification_table,
            reverse_cleanup,
        ),
    ]