#!/usr/bin/env python
"""
Simple test script to verify document upload functionality
"""
import os
import sys
import django

# Add the project directory to the Python path
sys.path.append('/home/ismail/projects/ats/kaauh_ats')

# Set up Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'NorahUniversity.settings')
django.setup()

from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth import get_user_model
from recruitment.models import JobPosting, Application, Document
from django.core.files.uploadedfile import SimpleUploadedFile

User = get_user_model()

def test_document_upload():
    """Test document upload functionality"""
    print("Testing document upload functionality...")

    # Clean up existing test data
    User.objects.filter(username__startswith='testcandidate').delete()

    # Create test data
    client = Client()

    # Create a test user with unique username
    import uuid
    unique_id = str(uuid.uuid4())[:8]
    user = User.objects.create_user(
        username=f'testcandidate_{unique_id}',
        email=f'test_{unique_id}@example.com',
        password='testpass123',
        user_type='candidate'
    )

    # Create a test job
    from datetime import date, timedelta
    job = JobPosting.objects.create(
        title='Test Job',
        description='Test Description',
        open_positions=1,
        status='ACTIVE',
        application_deadline=date.today() + timedelta(days=30)
    )

    # Create a test person first
    from recruitment.models import Person
    person = Person.objects.create(
        first_name='Test',
        last_name='Candidate',
        email=f'test_{unique_id}@example.com',
        phone='1234567890',
        user=user
    )

    # Create a test application
    application = Application.objects.create(
        job=job,
        person=person
    )

    # Log in the user
    client.login(username=f'testcandidate_{unique_id}', password='testpass123')

    # Test document upload URL
    url = reverse('document_upload', kwargs={'slug': application.slug})
    print(f"Document upload URL: {url}")

    # Create a test file
    test_file = SimpleUploadedFile(
        "test_document.pdf",
        b"file_content",
        content_type="application/pdf"
    )

    # Test POST request
    response = client.post(url, {
        'document_type': 'resume',
        'description': 'Test document',
        'file': test_file
    })

    print(f"Response status: {response.status_code}")

    if response.status_code == 200:
        data = response.json()
        print(f"Response data: {data}")
        if data.get('success'):
            print("✅ Document upload test PASSED")
        else:
            print(f"❌ Document upload test FAILED: {data.get('error')}")
    else:
        print(f"❌ Document upload test FAILED: HTTP {response.status_code}")

    # Clean up
    Document.objects.filter(object_id=application.id, content_type__model='application').delete()
    application.delete()
    job.delete()
    user.delete()

    print("Test completed.")

if __name__ == '__main__':
    test_document_upload()
