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


class JobSource(models.Model):
    class Family(models.TextChoices):
        PORTAL = "portal", "National portal"
        AGENCY = "agency", "Interim agency"
        COMPANY = "company", "Company careers"

    class Status(models.TextChoices):
        PLANNED = "planned", "Planned"
        ACTIVE = "active", "Active"
        PAUSED = "paused", "Paused"
        ERROR = "error", "Needs attention"

    name = models.CharField(max_length=160)
    family = models.CharField(max_length=24, choices=Family.choices)
    url = models.URLField(unique=True)
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.PLANNED)
    owner = models.CharField(max_length=120, blank=True)
    notes = models.TextField(blank=True)
    last_checked_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["family", "name"]
        indexes = [
            models.Index(fields=["family", "status"]),
            models.Index(fields=["name"]),
        ]

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("source_success", args=[self.pk])


class JobPosting(models.Model):
    class ContractType(models.TextChoices):
        CDI = "cdi", "CDI"
        CDD = "cdd", "CDD"
        INTERIM = "interim", "Interim"
        APPRENTICESHIP = "apprenticeship", "Apprenticeship"
        FREELANCE = "freelance", "Freelance"
        OTHER = "other", "Other"

    source = models.ForeignKey(JobSource, on_delete=models.PROTECT, related_name="jobs")
    title = models.CharField(max_length=220)
    company = models.CharField(max_length=180)
    location = models.CharField(max_length=160, default="Dijon, Bourgogne-Franche-Comté")
    contract_type = models.CharField(max_length=24, choices=ContractType.choices, default=ContractType.CDI)
    remote = models.BooleanField(default=False)
    salary = models.CharField(max_length=120, blank=True)
    apply_url = models.URLField(blank=True)
    published_at = models.DateField(default=timezone.localdate)
    description = models.TextField()
    is_active = models.BooleanField(default=True)
    duplicate_score = models.DecimalField(max_digits=5, decimal_places=2, default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-published_at", "-created_at"]
        indexes = [
            models.Index(fields=["is_active", "published_at"]),
            models.Index(fields=["company", "title"]),
            models.Index(fields=["contract_type"]),
        ]

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

    def get_absolute_url(self):
        return reverse("job_detail", args=[self.pk])
