
#!/usr/bin/env python3
"""
Test Complete Job Management System - CHUNK B
Tests job creation, applications, and management workflows
"""

import requests
import json
import time

BASE_URL = "http://0.0.0.0:5000/api"

def test_job_management_workflow():
    """Test complete job management workflow"""
    
    print("🔨 TESTING COMPLETE JOB MANAGEMENT SYSTEM")
    print("=" * 60)
    
    # Step 1: Register contractor and worker
    print("\n📝 Step 1: Register users")
    
    # Register contractor
    contractor_data = {
        'email': 'contractor@test.com',
        'password': 'SecurePass123!',
        'first_name': 'John',
        'last_name': 'Builder',
        'role': 'contractor',
        'phone_number': '0412345678',
        'location': 'Sydney, NSW',
        'abn_number': '12345678901',
        'business_name': 'Builder Bros Construction',
        'gst_registered': True
    }
    
    contractor_response = requests.post(f"{BASE_URL}/auth/register", json=contractor_data)
    print(f"   Contractor registration: {contractor_response.status_code}")
    
    if contractor_response.status_code == 201:
        contractor_token = contractor_response.json()['access_token']
        print("   ✅ Contractor registered successfully")
    else:
        print(f"   ❌ Contractor registration failed: {contractor_response.text}")
        return
    
    # Register worker
    worker_data = {
        'email': 'worker@test.com',
        'password': 'SecurePass123!',
        'first_name': 'Mike',
        'last_name': 'Carpenter',
        'role': 'worker',
        'phone_number': '0487654321',
        'location': 'Sydney, NSW',
        'abn_number': '98765432109',
        'primary_trade': 'Carpentry',
        'gst_registered': False
    }
    
    worker_response = requests.post(f"{BASE_URL}/auth/register", json=worker_data)
    print(f"   Worker registration: {worker_response.status_code}")
    
    if worker_response.status_code == 201:
        worker_token = worker_response.json()['access_token']
        print("   ✅ Worker registered successfully")
    else:
        print(f"   ❌ Worker registration failed: {worker_response.text}")
        return
    
    # Step 2: Get categories
    print("\n📋 Step 2: Get job categories")
    categories_response = requests.get(f"{BASE_URL}/marketplace/categories")
    print(f"   Categories response: {categories_response.status_code}")
    
    if categories_response.status_code == 200:
        categories = categories_response.json()['categories']
        if categories:
            category_id = categories[0]['id']
            category_name = categories[0]['name']
            print(f"   ✅ Found {len(categories)} categories, using: {category_name}")
        else:
            print("   ❌ No categories found")
            return
    else:
        print(f"   ❌ Failed to get categories: {categories_response.text}")
        return
    
    # Step 3: Contractor creates job
    print("\n🔨 Step 3: Create job posting")
    
    job_data = {
        'title': 'Kitchen Renovation - Carpentry Work',
        'description': 'Need experienced carpenter for kitchen renovation. Must have cabinet installation experience.',
        'category_id': category_id,
        'location': 'Bondi, NSW',
        'budget_min': 2500,
        'budget_max': 4000,
        'whs_requirements': 'White card required. Safety glasses and steel cap boots mandatory.',
        'white_card_required': True,
        'insurance_required': True
    }
    
    headers = {'Authorization': f'Bearer {contractor_token}'}
    job_response = requests.post(f"{BASE_URL}/marketplace/jobs", json=job_data, headers=headers)
    print(f"   Job creation response: {job_response.status_code}")
    
    if job_response.status_code == 201:
        job_id = job_response.json()['job_id']
        print(f"   ✅ Job created successfully (ID: {job_id})")
    else:
        print(f"   ❌ Job creation failed: {job_response.text}")
        return
    
    # Step 4: Worker applies to job
    print("\n🤝 Step 4: Worker applies to job")
    
    application_data = {
        'proposed_rate': 3200,
        'cover_letter': 'Experienced carpenter with 8 years in kitchen renovations. Have all required safety certifications.'
    }
    
    worker_headers = {'Authorization': f'Bearer {worker_token}'}
    apply_response = requests.post(f"{BASE_URL}/marketplace/jobs/{job_id}/apply", json=application_data, headers=worker_headers)
    print(f"   Application response: {apply_response.status_code}")
    
    if apply_response.status_code == 201:
        application_id = apply_response.json()['application_id']
        print(f"   ✅ Application submitted successfully (ID: {application_id})")
    else:
        print(f"   ❌ Application failed: {apply_response.text}")
        return
    
    # Step 5: Contractor views applications
    print("\n👔 Step 5: Contractor views applications")
    
    applications_response = requests.get(f"{BASE_URL}/marketplace/jobs/{job_id}/applications", headers=headers)
    print(f"   Applications response: {applications_response.status_code}")
    
    if applications_response.status_code == 200:
        applications = applications_response.json()['applications']
        print(f"   ✅ Found {len(applications)} applications")
        if applications:
            app = applications[0]
            print(f"      - Worker: {app['worker']['name']}")
            print(f"      - Rate: ${app['proposed_rate']}")
            print(f"      - Status: {app['status']}")
    else:
        print(f"   ❌ Failed to get applications: {applications_response.text}")
        return
    
    # Step 6: Contractor accepts application
    print("\n✅ Step 6: Accept application")
    
    accept_data = {'status': 'accepted'}
    accept_response = requests.put(f"{BASE_URL}/marketplace/applications/{application_id}", json=accept_data, headers=headers)
    print(f"   Accept application response: {accept_response.status_code}")
    
    if accept_response.status_code == 200:
        print("   ✅ Application accepted successfully")
    else:
        print(f"   ❌ Accept application failed: {accept_response.text}")
    
    # Step 7: Check contractor's jobs
    print("\n📊 Step 7: Contractor dashboard")
    
    my_jobs_response = requests.get(f"{BASE_URL}/marketplace/my-jobs", headers=headers)
    print(f"   My jobs response: {my_jobs_response.status_code}")
    
    if my_jobs_response.status_code == 200:
        my_jobs = my_jobs_response.json()['jobs']
        print(f"   ✅ Contractor has {len(my_jobs)} jobs")
        if my_jobs:
            job = my_jobs[0]
            print(f"      - Job: {job['title']}")
            print(f"      - Status: {job['status']}")
            print(f"      - Applications: {job['applications_count']}")
    else:
        print(f"   ❌ Failed to get contractor jobs: {my_jobs_response.text}")
    
    # Step 8: Check worker's applications
    print("\n🔍 Step 8: Worker application history")
    
    worker_apps_response = requests.get(f"{BASE_URL}/marketplace/my-applications", headers=worker_headers)
    print(f"   My applications response: {worker_apps_response.status_code}")
    
    if worker_apps_response.status_code == 200:
        worker_apps = worker_apps_response.json()['applications']
        print(f"   ✅ Worker has {len(worker_apps)} applications")
        if worker_apps:
            app = worker_apps[0]
            print(f"      - Job: {app['job']['title']}")
            print(f"      - Status: {app['status']}")
            print(f"      - Rate: ${app['proposed_rate']}")
    else:
        print(f"   ❌ Failed to get worker applications: {worker_apps_response.text}")
    
    print("\n🎉 JOB MANAGEMENT WORKFLOW COMPLETE!")
    print("=" * 60)
    print("✅ Registration: Both contractor and worker")
    print("✅ Job Creation: Contractor posted job with WHS requirements")
    print("✅ Job Application: Worker applied with proposed rate")
    print("✅ Application Management: Contractor accepted application")
    print("✅ Dashboard Views: Both users can view their jobs/applications")
    print("\n🚀 CHUNK B - Job Management System is fully operational!")

if __name__ == "__main__":
    test_job_management_workflow()
