from django.db import models
from django.utils.text import slugify

class Job(models.Model):
    EMPLOYMENT_CHOICES = [
        ('full_time', 'Full-time'),
        ('part_time', 'Part-time'),
        ('contract', 'Contract'),
        ('remote', 'Remote'),
        ('hybrid', 'Hybrid'),
    ]
    title = models.CharField(max_length=150)
    slug = models.SlugField(unique=True, blank=True)
    department = models.CharField(max_length=100, default="Software Engineering")
    location = models.CharField(max_length=100, default="Dar es Salaam, Tanzania (Hybrid)")
    employment_type = models.CharField(max_length=30, choices=EMPLOYMENT_CHOICES, default='full_time')
    experience_level = models.CharField(max_length=50, default="Mid - Senior Level (3+ years)")
    description = models.TextField()
    responsibilities = models.JSONField(default=list)
    requirements = models.JSONField(default=list)
    benefits = models.JSONField(default=list)
    deadline = models.DateField()
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name = "Career Opening"
        verbose_name_plural = "Career Openings"

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.title} ({self.department})"


class JobApplication(models.Model):
    STATUS_CHOICES = [
        ('new', 'New Application'),
        ('shortlisted', 'Shortlisted'),
        ('interview', 'Interview Scheduled'),
        ('rejected', 'Not Selected'),
        ('hired', 'Hired'),
    ]
    job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applications')
    full_name = models.CharField(max_length=150)
    email = models.EmailField()
    phone = models.CharField(max_length=50)
    cv_file = models.FileField(upload_to='cv_uploads/', blank=True, null=True)
    cover_letter = models.TextField(blank=True)
    linkedin_url = models.URLField(blank=True)
    portfolio_url = models.URLField(blank=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='new')
    notes = models.TextField(blank=True, help_text="Internal HR evaluation notes")
    applied_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-applied_at']
        verbose_name = "Job Application"
        verbose_name_plural = "Job Applications"

    def __str__(self):
        return f"{self.full_name} - {self.job.title}"
