#!/usr/bin/env python
"""
Script to verify user status and credentials in the database
"""
import os
import django
from datetime import datetime

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.contrib.auth import get_user_model, authenticate
from django.contrib.auth.hashers import make_password, check_password

User = get_user_model()

def verify_user(email, password):
    """Verify a user's status and credentials"""
    print(f"\nChecking user: {email}")
    print("-" * 50)
    
    try:
        # Get user from database
        user = User.objects.get(email=email)
        print("✅ User found in database")
        print(f"Username: {user.username}")
        print(f"Email: {user.email}")
        print(f"Role: {user.role}")
        print(f"Status: {user.status}")
        print(f"Is Active: {user.is_active}")
        print(f"Is Staff: {user.is_staff}")
        print(f"Is Superuser: {user.is_superuser}")
        print(f"Date Joined: {user.date_joined}")
        print(f"Last Login: {user.last_login}")
        
        # Check password
        if check_password(password, user.password):
            print("✅ Stored password hash is valid")
        else:
            print("❌ Stored password hash is invalid")
            
            # Create correct password hash
            correct_hash = make_password(password)
            print(f"\nCorrect password hash should be:")
            print(correct_hash)
            print("\nCurrent password hash is:")
            print(user.password)
        
        # Test authentication
        auth_user = authenticate(username=email, password=password)
        if auth_user:
            print("✅ Authentication successful")
        else:
            print("❌ Authentication failed")
            
    except User.DoesNotExist:
        print("❌ User not found in database")
    except Exception as e:
        print(f"❌ Error: {str(e)}")

def main():
    """Main function to verify users"""
    print("Verifying Users in Database")
    print("=" * 50)
    
    # Test credentials
    credentials = [
        ('admin@branchbusinessadvance.com', 'admin123'),
        ('officer@branchbusinessadvance.com', 'officer123'),
        ('client@branchbusinessadvance.com', 'client123'),
    ]
    
    for email, password in credentials:
        verify_user(email, password)
    
    print("\n" + "=" * 50)
    print("User verification completed!")
    print("\nIf passwords are invalid, you can update them using:")
    print("python manage.py shell")
    print('>>> from django.contrib.auth import get_user_model')
    print('>>> User = get_user_model()')
    print('>>> user = User.objects.get(email="user@email.com")')
    print('>>> user.set_password("newpassword")')
    print('>>> user.save()')

if __name__ == '__main__':
    main() 