from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _


class CaliberStatus(models.TextChoices):
    PENDING  = 'PENDING',  _('Pending Verification')
    VERIFIED = 'VERIFIED', _('Verified')
    REJECTED = 'REJECTED', _('Rejected')


class Caliber(models.Model):
    name             = models.CharField(_('name'), max_length=100, unique=True)
    short_name       = models.CharField(_('short name'), max_length=50, blank=True)

    # CIP standard dimensions
    case_length_mm        = models.DecimalField(
        _('case length (mm)'), max_digits=5, decimal_places=2, null=True, blank=True
    )
    overall_length_mm     = models.DecimalField(
        _('overall length (mm)'), max_digits=5, decimal_places=2, null=True, blank=True
    )
    bullet_diameter_mm    = models.DecimalField(
        _('bullet diameter (mm)'), max_digits=5, decimal_places=2, null=True, blank=True
    )
    case_head_diameter_mm = models.DecimalField(
        _('case head diameter (mm)'), max_digits=5, decimal_places=2, null=True, blank=True
    )
    rim_diameter_mm       = models.DecimalField(
        _('rim diameter (mm)'), max_digits=5, decimal_places=2, null=True, blank=True
    )
    max_pressure_mpa      = models.DecimalField(
        _('max pressure (MPa)'), max_digits=6, decimal_places=1, null=True, blank=True
    )
    notes = models.TextField(_('notes'), blank=True)

    # Moderation
    status = models.CharField(
        _('status'), max_length=10, choices=CaliberStatus.choices, default=CaliberStatus.PENDING
    )
    submitted_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, null=True, blank=True,
        on_delete=models.SET_NULL, related_name='submitted_calibers',
        verbose_name=_('submitted by'),
    )
    reviewed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, null=True, blank=True,
        on_delete=models.SET_NULL, related_name='reviewed_calibers',
        verbose_name=_('reviewed by'),
    )
    reviewed_at = models.DateTimeField(_('reviewed at'), null=True, blank=True)
    created_at  = models.DateTimeField(_('created at'), auto_now_add=True)
    updated_at  = models.DateTimeField(_('updated at'), auto_now=True)

    class Meta:
        verbose_name        = _('caliber')
        verbose_name_plural = _('calibers')
        ordering = ['name']

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

    def verify(self, reviewed_by):
        self.status = CaliberStatus.VERIFIED
        self.reviewed_by = reviewed_by
        self.reviewed_at = timezone.now()
        self.save(update_fields=['status', 'reviewed_by', 'reviewed_at'])

    def reject(self, reviewed_by):
        self.status = CaliberStatus.REJECTED
        self.reviewed_by = reviewed_by
        self.reviewed_at = timezone.now()
        self.save(update_fields=['status', 'reviewed_by', 'reviewed_at'])
