from django.db import models
from django.contrib.auth.models import User

class MachineModel(models.Model):
    name = models.CharField("Nombre", max_length=200)
    brand = models.CharField("Marca", max_length=100)
    manual_pdf = models.FileField("Manual (PDF)", upload_to='manuals/', blank=True, null=True)

    class Meta:
        verbose_name = "Modelo de Máquina"
        verbose_name_plural = "Modelos de Máquinas"

    def __str__(self):
        return f"{self.brand} {self.name}"

class SparePart(models.Model):
    reference_code = models.CharField("Código de Referencia", max_length=100, unique=True)
    name = models.CharField("Nombre", max_length=200)
    description = models.TextField("Descripción", blank=True)
    stock_quantity = models.PositiveIntegerField("Cantidad en Stock", default=0)
    low_stock_threshold = models.PositiveIntegerField("Umbral de Stock Bajo", default=10)

    class Meta:
        verbose_name = "Repuesto"
        verbose_name_plural = "Repuestos"

    def __str__(self):
        return self.name

class ServiceIntervention(models.Model):
    STATUS_CHOICES = [
        ('PENDING', 'Pendiente'),
        ('IN_PROGRESS', 'En Progreso'),
        ('COMPLETED', 'Completada'),
        ('CANCELLED', 'Cancelada'),
    ]

    machine = models.ForeignKey(MachineModel, on_delete=models.CASCADE, related_name='interventions', verbose_name="Máquina")
    technician = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='interventions', verbose_name="Técnico")
    status = models.CharField("Estado", max_length=20, choices=STATUS_CHOICES, default='PENDING')
    description = models.TextField("Descripción")
    created_at = models.DateTimeField("Fecha de Creación", auto_now_add=True)
    resolved_at = models.DateTimeField("Fecha de Resolución", null=True, blank=True)

    class Meta:
        verbose_name = "Intervención de Servicio"
        verbose_name_plural = "Intervenciones de Servicio"

    def __str__(self):
        return f"Intervención para {self.machine} el {self.created_at.strftime('%d-%m-%Y')}"