#!/usr/bin/env python
"""Create a test pending client for testing the approval system"""

import os
import sys
import django
from pathlib import Path

# Setup Django
sys.path.insert(0, str(Path(__file__).resolve().parent))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.contrib.auth import get_user_model
from users.models import CustomUser, Branch
from django.utils import timezone
from datetime import date
import uuid

User = get_user_model()

def create_test_pending_client():
    """Create a test client with pending_approval status"""
    
    # Get or create a test branch
    branch, _ = Branch.objects.get_or_create(
        name='Test Branch',
        defaults={
            'code': 'TEST',
            'is_active': True,
            'is_main_branch': False
        }
    )
    
    # Generate unique identifiers
    timestamp = int(timezone.now().timestamp())
    test_id = f"TEST{timestamp}"
    phone = f"+254712{timestamp % 1000000:06d}"
    
    # Check if user already exists
    if CustomUser.objects.filter(username=phone).exists():
        print(f"Test user with phone {phone} already exists. Updating to pending_approval status...")
        user = CustomUser.objects.get(username=phone)
        user.status = 'pending_approval'
        user.is_active = False
        user.is_verified = False
        user.save()
        print(f"[OK] Updated existing user: {user.get_full_name()}")
        return user
    
    # Create new test user
    try:
        user = CustomUser.objects.create_user(
            username=phone,
            phone_number=phone,
            email=f"test{timestamp}@example.com",
            first_name="Test",
            last_name="Client",
            id_number=test_id,
            role='borrower',
            status='pending_approval',
            is_active=False,
            is_verified=False,
            branch=branch,
            date_of_birth=date(1990, 1, 1),
            gender='M',
            nationality='Kenyan',
            business_name='Test Business LTD',
            business_type='retail',
            monthly_income=50000,
            physical_address='123 Test Street',
            city='Nairobi',
            county='Nairobi',
            postal_code='00100'
        )
        
        print("=" * 80)
        print("[OK] TEST CLIENT CREATED SUCCESSFULLY")
        print("=" * 80)
        print(f"\nClient Details:")
        print(f"  Name: {user.get_full_name()}")
        print(f"  ID Number: {user.id_number}")
        print(f"  Phone: {user.phone_number}")
        print(f"  Email: {user.email}")
        print(f"  Business: {user.business_name}")
        print(f"  Status: {user.status}")
        print(f"  Branch: {user.branch.name if user.branch else 'None'}")
        print(f"\nThis client should appear in the 'Pending Approvals' page")
        print(f"and require admin approval to become active.")
        print("\nNext steps:")
        print("1. Go to the Clients page")
        print("2. Click 'Pending Approvals' button")
        print("3. You should see this test client listed")
        print("4. Test the approve/reject functionality")
        print("=" * 80)
        
        return user
        
    except Exception as e:
        print(f"[FAIL] Failed to create test client: {e}")
        import traceback
        traceback.print_exc()
        return None


if __name__ == '__main__':
    create_test_pending_client()

