from django.db import models
from django.conf import settings
from django.urls import reverse
from django.utils import timezone
from django.core.exceptions import ValidationError
import os


def application_file_path(instance, filename):
    """Generate file path for application uploads"""
    return f'applications/{instance.job.id}/{instance.id}/{filename}'


def validate_pdf_file(file):
    """Validate that uploaded file is a PDF"""
    if not file.name.lower().endswith('.pdf'):
        raise ValidationError('File must be in PDF format.')
    if file.size > 10 * 1024 * 1024:  # 10MB
        raise ValidationError('File size cannot exceed 10MB.')


class JobPosting(models.Model):
    """Job posting model"""
    
    STATUS_CHOICES = [
        ('draft', 'Draft'),
        ('published', 'Published'),
        ('closed', 'Closed'),
        ('archived', 'Archived'),
    ]
    
    title = models.CharField(max_length=200)
    description = models.TextField()
    requirements = models.TextField()
    location = models.CharField(max_length=200)
    application_deadline = models.DateTimeField()
    posted_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='job_postings'
    )
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='draft'
    )
    
    # Additional fields
    salary_range = models.CharField(max_length=100, blank=True)
    employment_type = models.CharField(
        max_length=50,
        choices=[
            ('full_time', 'Full Time'),
            ('part_time', 'Part Time'),
            ('contract', 'Contract'),
            ('internship', 'Internship'),
        ],
        default='full_time'
    )
    experience_level = models.CharField(
        max_length=50,
        choices=[
            ('entry', 'Entry Level'),
            ('mid', 'Mid Level'),
            ('senior', 'Senior Level'),
            ('executive', 'Executive'),
        ],
        default='mid'
    )
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['status', 'application_deadline']),
            models.Index(fields=['posted_by']),
            models.Index(fields=['created_at']),
        ]
    
    def __str__(self):
        return self.title
    
    def get_absolute_url(self):
        return reverse('jobs:job_detail', kwargs={'pk': self.pk})
    
    @property
    def is_active(self):
        return (self.status == 'published' and 
                self.application_deadline.date() >= timezone.now().date())
    
    @property
    def application_count(self):
        return self.applications.count()


class Application(models.Model):
    """Job application model - simplified without status tracking"""
    
    job = models.ForeignKey(
        JobPosting,
        on_delete=models.CASCADE,
        related_name='applications'
    )
    
    # Applicant information (now requires authentication)
    applicant_name = models.CharField(max_length=200)
    applicant_email = models.EmailField()
    applicant_phone = models.CharField(max_length=20)
    membership_number = models.CharField(max_length=50)
    
    # Link to authenticated user (required)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='applications'
    )
    
    # Application content
    cover_letter = models.TextField()
    resume = models.FileField(upload_to=application_file_path)
    ictaz_certificate = models.FileField(
        upload_to='applications/certificates/',
        help_text='Upload your ICTAZ membership certificate (PDF format, max 10MB)',
        validators=[validate_pdf_file]
    )
    additional_documents = models.FileField(
        upload_to=application_file_path,
        help_text="Upload additional documents (NRC, Degree Results, etc.) as a single PDF"
    )
    
    # Timestamps
    submitted_at = models.DateTimeField(auto_now_add=True)
    
    # Admin notes
    admin_notes = models.TextField(blank=True)
    
    class Meta:
        ordering = ['submitted_at']  # First come, first served
        indexes = [
            models.Index(fields=['job']),
            models.Index(fields=['applicant_email']),
            models.Index(fields=['membership_number']),
            models.Index(fields=['submitted_at']),
        ]
        unique_together = ['job', 'user']  # Prevent duplicate applications per user
    
    def __str__(self):
        return f"{self.applicant_name} - {self.job.title}"
    
    def get_absolute_url(self):
        return reverse('jobs:application_detail', kwargs={'pk': self.pk})
    
    @property
    def is_member(self):
        return bool(self.membership_number)
    
    def delete(self, *args, **kwargs):
        """Delete associated files when application is deleted"""
        if self.resume:
            if os.path.isfile(self.resume.path):
                os.remove(self.resume.path)
        if self.ictaz_certificate:
            if os.path.isfile(self.ictaz_certificate.path):
                os.remove(self.ictaz_certificate.path)
        if self.additional_documents:
            if os.path.isfile(self.additional_documents.path):
                os.remove(self.additional_documents.path)
        super().delete(*args, **kwargs)
