from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.text import slugify


class JobOffer(models.Model):
    class Status(models.TextChoices):
        DRAFT     = 'draft',     'Brouillon'
        PUBLISHED = 'published', 'Publié'
        CLOSED    = 'closed',    'Fermé'

    class ContractType(models.TextChoices):
        CDI       = 'CDI',       'CDI'
        CDD       = 'CDD',       'CDD'
        STAGE     = 'stage',     'Stage'
        FREELANCE = 'freelance', 'Freelance'

    class Department(models.TextChoices):
        TECH  = 'tech',  'Technologie'
        AGRO  = 'agro',  'Agronomie'
        OPS   = 'ops',   'Opérations'
        SALES = 'sales', 'Commercial'
        ADMIN = 'admin', 'Administration'

    title                = models.CharField(max_length=200, verbose_name='Intitulé du poste')
    slug                 = models.SlugField(max_length=220, unique=True)
    department           = models.CharField(max_length=20, choices=Department.choices, verbose_name='Département')
    contract_type        = models.CharField(max_length=20, choices=ContractType.choices, verbose_name='Type de contrat')
    location             = models.CharField(max_length=150, default="Abidjan, Côte d'Ivoire", verbose_name='Lieu')
    is_remote            = models.BooleanField(default=False, verbose_name='Télétravail possible')
    description          = models.TextField(verbose_name='Description du poste')
    requirements         = models.TextField(verbose_name='Compétences requises')
    nice_to_have         = models.TextField(blank=True, verbose_name='Compétences souhaitées')
    salary_range         = models.CharField(max_length=100, blank=True, verbose_name='Fourchette salariale')
    status               = models.CharField(max_length=20, choices=Status.choices, default=Status.DRAFT, db_index=True, verbose_name='Statut')
    application_deadline = models.DateField(null=True, blank=True, verbose_name='Date limite de candidature')
    published_at         = models.DateTimeField(null=True, blank=True, verbose_name='Publié le')
    created_at           = models.DateTimeField(auto_now_add=True)
    updated_at           = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-published_at', '-created_at']
        verbose_name = "Offre d'emploi"
        verbose_name_plural = "Offres d'emploi"

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

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        if self.status == self.Status.PUBLISHED and not self.published_at:
            self.published_at = timezone.now()
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('careers:job_detail', kwargs={'slug': self.slug})

    @property
    def is_open(self):
        if self.status != self.Status.PUBLISHED:
            return False
        if self.application_deadline and self.application_deadline < timezone.now().date():
            return False
        return True


class JobApplication(models.Model):
    class Status(models.TextChoices):
        NEW       = 'new',       'Nouvelle'
        REVIEWING = 'reviewing', "En cours d'examen"
        SHORTLIST = 'shortlist', 'Présélectionné(e)'
        INTERVIEW = 'interview', 'Entretien planifié'
        REJECTED  = 'rejected',  'Rejeté(e)'
        HIRED     = 'hired',     'Recruté(e)'

    job           = models.ForeignKey(JobOffer, on_delete=models.CASCADE, related_name='applications', verbose_name='Offre')
    first_name    = models.CharField(max_length=100, verbose_name='Prénom')
    last_name     = models.CharField(max_length=100, verbose_name='Nom de famille')
    email         = models.EmailField(verbose_name='Email')
    phone         = models.CharField(max_length=30, blank=True, verbose_name='Téléphone')
    linkedin_url  = models.URLField(blank=True, verbose_name='LinkedIn')
    cover_letter  = models.TextField(verbose_name='Lettre de motivation')
    cv_file       = models.FileField(upload_to='careers/cvs/%Y/%m/', verbose_name='CV')
    portfolio_url = models.URLField(blank=True, verbose_name='Portfolio / GitHub')
    status        = models.CharField(max_length=20, choices=Status.choices, default=Status.NEW, db_index=True, verbose_name='Statut')
    admin_notes   = models.TextField(blank=True, verbose_name='Notes internes')
    applied_at    = models.DateTimeField(auto_now_add=True, verbose_name='Candidaté le')
    updated_at    = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-applied_at']
        verbose_name = 'Candidature'
        verbose_name_plural = 'Candidatures'
        unique_together = [('job', 'email')]

    def __str__(self):
        return f"{self.first_name} {self.last_name} → {self.job.title}"

    @property
    def full_name(self):
        return f"{self.first_name} {self.last_name}"
