import pytest
from app.models import User, Folder, ProcessedEmail, db
from app import create_app


class TestFolderDeletion:
    def test_delete_folder_with_emails(self, app, mock_user, authenticated_client):
        """Test that deleting a folder also deletes its associated emails."""
        with app.app_context():
            # Create a folder
            folder = Folder(
                user_id=mock_user.id,
                name='Test Folder',
                rule_text='Test rule'
            )
            db.session.add(folder)
            db.session.commit()
            
            # Create some email records associated with this folder
            email_records = [
                ProcessedEmail(
                    user_id=mock_user.id,
                    folder_id=folder.id,
                    folder_name='Test Folder',
                    email_uid='123',
                    is_processed=False
                ),
                ProcessedEmail(
                    user_id=mock_user.id,
                    folder_id=folder.id,
                    folder_name='Test Folder',
                    email_uid='456',
                    is_processed=False
                )
            ]
            db.session.bulk_save_objects(email_records)
            db.session.commit()
            
            # Verify emails were created
            assert ProcessedEmail.query.count() == 2
            
            # Delete the folder
            response = authenticated_client.delete(f'/api/folders/{folder.id}')
            
            # Verify the response is successful
            assert response.status_code == 200
            
            # Verify the folder is deleted
            deleted_folder = Folder.query.filter_by(id=folder.id).first()
            assert deleted_folder is None
            
            # Verify the associated emails are also deleted (cascade delete)
            assert ProcessedEmail.query.count() == 0
    
    def test_delete_folder_with_no_emails(self, app, mock_user, authenticated_client):
        """Test that deleting a folder with no associated emails works normally."""
        with app.app_context():
            # Create a folder
            folder = Folder(
                user_id=mock_user.id,
                name='Test Folder',
                rule_text='Test rule'
            )
            db.session.add(folder)
            db.session.commit()
            
            # Verify no emails are associated with this folder
            assert ProcessedEmail.query.filter_by(folder_id=folder.id).count() == 0
            
            # Delete the folder
            response = authenticated_client.delete(f'/api/folders/{folder.id}')
            
            # Verify the response is successful
            assert response.status_code == 200
            
            # Verify the folder is deleted
            deleted_folder = Folder.query.filter_by(id=folder.id).first()
            assert deleted_folder is None