#!/usr/bin/env python
"""
Test script to verify contact information updates in the database
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection
from reports.models import SystemSettings

def test_system_settings_mpesa_shortcode():
    """Test that system settings has the correct M-Pesa shortcode"""
    print("\n" + "=" * 80)
    print("TEST 1: System Settings M-Pesa Shortcode")
    print("=" * 80)
    
    try:
        settings = SystemSettings.objects.first()
        
        if not settings:
            print("✗ FAIL: No system settings found")
            return False
        
        expected_shortcode = '4159523'
        actual_shortcode = settings.mpesa_business_shortcode
        
        if actual_shortcode == expected_shortcode:
            print(f"✓ PASS: M-Pesa shortcode is correct: {actual_shortcode}")
            return True
        else:
            print(f"✗ FAIL: M-Pesa shortcode mismatch")
            print(f"  Expected: {expected_shortcode}")
            print(f"  Actual: {actual_shortcode}")
            return False
            
    except Exception as e:
        print(f"✗ FAIL: Error checking system settings: {str(e)}")
        return False


def test_no_old_domain_emails():
    """Test that no user emails contain old domain"""
    print("\n" + "=" * 80)
    print("TEST 2: No Old Domain Emails")
    print("=" * 80)
    
    try:
        with connection.cursor() as cursor:
            cursor.execute("""
                SELECT COUNT(*) 
                FROM users 
                WHERE email LIKE '%branchbusinessadvance%' 
                   OR email LIKE '%branch%business%advance%'
            """)
            
            count = cursor.fetchone()[0]
            
            if count == 0:
                print(f"✓ PASS: No users with old domain emails found")
                return True
            else:
                print(f"✗ FAIL: Found {count} users with old domain emails")
                return False
                
    except Exception as e:
        print(f"✗ FAIL: Error checking user emails: {str(e)}")
        return False


def test_no_old_phone_numbers():
    """Test that no old phone numbers are stored"""
    print("\n" + "=" * 80)
    print("TEST 3: No Old Phone Numbers")
    print("=" * 80)
    
    old_phone_patterns = [
        '+254720246513',
        '0720246513',
    ]
    
    try:
        with connection.cursor() as cursor:
            found_old_numbers = False
            
            for pattern in old_phone_patterns:
                cursor.execute("""
                    SELECT COUNT(*) 
                    FROM users 
                    WHERE phone_number LIKE %s
                """, (f'%{pattern}%',))
                
                count = cursor.fetchone()[0]
                
                if count > 0:
                    print(f"✗ FAIL: Found {count} users with old phone number pattern: {pattern}")
                    found_old_numbers = True
            
            if not found_old_numbers:
                print(f"✓ PASS: No old phone numbers found in user records")
                return True
            else:
                return False
                
    except Exception as e:
        print(f"✗ FAIL: Error checking phone numbers: {str(e)}")
        return False


def test_system_settings_notifications_enabled():
    """Test that notification settings are properly configured"""
    print("\n" + "=" * 80)
    print("TEST 4: Notification Settings")
    print("=" * 80)
    
    try:
        settings = SystemSettings.objects.first()
        
        if not settings:
            print("✗ FAIL: No system settings found")
            return False
        
        if settings.email_notifications_enabled and settings.sms_notifications_enabled:
            print(f"✓ PASS: Email and SMS notifications are enabled")
            return True
        else:
            print(f"✗ FAIL: Notifications not properly enabled")
            print(f"  Email notifications: {settings.email_notifications_enabled}")
            print(f"  SMS notifications: {settings.sms_notifications_enabled}")
            return False
            
    except Exception as e:
        print(f"✗ FAIL: Error checking notification settings: {str(e)}")
        return False


def test_grazuri_contact_info_documented():
    """Test that Grazuri contact information is documented"""
    print("\n" + "=" * 80)
    print("TEST 5: Grazuri Contact Information Documentation")
    print("=" * 80)
    
    grazuri_contacts = {
        'Company Name': 'Haven Grazuri Investment Limited',
        'Phone Numbers': '+254112941830, +254114457516, +254115451752',
        'WhatsApp': '+254112941830',
        'Email': 'info@havengrazuri.co.ke',
        'SMS Sender ID': 'HavGrazuri',
        'M-Pesa Shortcode': '4159523',
    }
    
    print("\nGrazuri Contact Information:")
    for key, value in grazuri_contacts.items():
        print(f"  {key}: {value}")
    
    print("\n✓ PASS: Grazuri contact information documented")
    return True


def generate_test_report(results):
    """Generate test summary report"""
    print("\n" + "=" * 80)
    print("TEST SUMMARY REPORT")
    print("=" * 80)
    
    total_tests = len(results)
    passed_tests = sum(results)
    failed_tests = total_tests - passed_tests
    
    print(f"\nTotal Tests: {total_tests}")
    print(f"Passed: {passed_tests}")
    print(f"Failed: {failed_tests}")
    
    if failed_tests == 0:
        print("\n✓ ALL TESTS PASSED!")
        print("=" * 80)
        return True
    else:
        print(f"\n✗ {failed_tests} TEST(S) FAILED")
        print("=" * 80)
        return False


def main():
    """Main test execution"""
    print("\n" + "=" * 80)
    print("CONTACT INFORMATION DATABASE UPDATE TESTS")
    print("Haven Grazuri Investment Limited")
    print("=" * 80)
    
    results = []
    
    # Run all tests
    results.append(test_system_settings_mpesa_shortcode())
    results.append(test_no_old_domain_emails())
    results.append(test_no_old_phone_numbers())
    results.append(test_system_settings_notifications_enabled())
    results.append(test_grazuri_contact_info_documented())
    
    # Generate report
    all_passed = generate_test_report(results)
    
    return 0 if all_passed else 1


if __name__ == '__main__':
    exit(main())
