from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from recruitment.models import HiringAgency, AgencyJobAssignment, JobPosting
from django.utils import timezone
import random

class Command(BaseCommand):
    help = 'Set up test agencies and assignments for messaging system testing'

    def handle(self, *args, **options):
        self.stdout.write('Setting up test agencies and assignments...')

        # Create test admin user if not exists
        admin_user, created = User.objects.get_or_create(
            username='testadmin',
            defaults={
                'email': 'admin@test.com',
                'first_name': 'Test',
                'last_name': 'Admin',
                'is_staff': True,
                'is_superuser': True,
            }
        )
        if created:
            admin_user.set_password('admin123')
            admin_user.save()
            self.stdout.write(self.style.SUCCESS('Created test admin user: testadmin/admin123'))

        # Create test agencies
        agencies_data = [
            {
                'name': 'Tech Talent Solutions',
                'contact_person': 'John Smith',
                'email': 'contact@techtalent.com',
                'phone': '+966501234567',
                'website': 'https://techtalent.com',
                'notes': 'Leading technology recruitment agency specializing in IT and software development roles.',
                'country': 'SA'
            },
            {
                'name': 'Healthcare Recruiters Ltd',
                'contact_person': 'Sarah Johnson',
                'email': 'info@healthcarerecruiters.com',
                'phone': '+966502345678',
                'website': 'https://healthcarerecruiters.com',
                'notes': 'Specialized healthcare recruitment agency for medical professionals and healthcare staff.',
                'country': 'SA'
            },
            {
                'name': 'Executive Search Partners',
                'contact_person': 'Michael Davis',
                'email': 'partners@execsearch.com',
                'phone': '+966503456789',
                'website': 'https://execsearch.com',
                'notes': 'Premium executive search firm for senior management and C-level positions.',
                'country': 'SA'
            }
        ]

        created_agencies = []
        for agency_data in agencies_data:
            agency, created = HiringAgency.objects.get_or_create(
                name=agency_data['name'],
                defaults=agency_data
            )
            if created:
                self.stdout.write(self.style.SUCCESS(f'Created agency: {agency.name}'))
            created_agencies.append(agency)

        # Get or create some sample jobs
        jobs = []
        job_titles = [
            'Senior Software Engineer',
            'Healthcare Administrator',
            'Marketing Manager',
            'Data Analyst',
            'HR Director'
        ]

        for title in job_titles:
            job, created = JobPosting.objects.get_or_create(
                internal_job_id=f'KAAUH-2025-{len(jobs)+1:06d}',
                defaults={
                    'title': title,
                    'description': f'Description for {title} position',
                    'qualifications': f'Requirements for {title}',
                    'location_city': 'Riyadh',
                    'location_country': 'Saudi Arabia',
                    'job_type': 'FULL_TIME',
                    'workplace_type': 'ON_SITE',
                    'application_deadline': timezone.now().date() + timezone.timedelta(days=60),
                    'status': 'ACTIVE',
                    'created_by': admin_user.username
                }
            )
            if created:
                self.stdout.write(self.style.SUCCESS(f'Created job: {job.title}'))
            jobs.append(job)

        # Create agency assignments
        for i, agency in enumerate(created_agencies):
            for j, job in enumerate(jobs[:2]):  # Assign 2 jobs per agency
                assignment, created = AgencyJobAssignment.objects.get_or_create(
                    agency=agency,
                    job=job,
                    defaults={
                        'max_candidates': 5,
                        'deadline_date': timezone.now() + timezone.timedelta(days=30),
                        'status': 'ACTIVE',
                        'is_active': True
                    }
                )
                if created:
                    self.stdout.write(self.style.SUCCESS(
                        f'Created assignment: {agency.name} -> {job.title}'
                    ))

        self.stdout.write(self.style.SUCCESS('Test agencies and assignments setup complete!'))
        self.stdout.write('\nSummary:')
        self.stdout.write(f'- Agencies: {HiringAgency.objects.count()}')
        self.stdout.write(f'- Jobs: {JobPosting.objects.count()}')
        self.stdout.write(f'- Assignments: {AgencyJobAssignment.objects.count()}')
