from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone

User = get_user_model()

class Report(models.Model):
    """Model to store reports submitted by users."""
    REPORT_TYPES = [
        ('weekly', 'Weekly Report'),
        ('monthly', 'Monthly Report'),
        ('quarterly', 'Quarterly Report'),
        ('annual', 'Annual Report'),
        ('ad_hoc', 'Ad Hoc Report'),
    ]
    
    STATUS_CHOICES = [
        ('draft', 'Draft'),
        ('submitted', 'Submitted'),
        ('reviewed', 'Reviewed'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
    ]
    
    title = models.CharField(max_length=200)
    report_type = models.CharField(max_length=20, choices=REPORT_TYPES, default='ad_hoc')
    period_start = models.DateField()
    period_end = models.DateField()
    content = models.TextField(help_text='Main report content')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
    file = models.FileField(upload_to='reports/%Y/%m/%d/', null=True, blank=True)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reports_created')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    submitted_at = models.DateTimeField(null=True, blank=True)
    reviewed_by = models.ForeignKey(
        User, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True, 
        related_name='reports_reviewed'
    )
    reviewed_at = models.DateTimeField(null=True, blank=True)
    review_notes = models.TextField(blank=True)
    
    class Meta:
        ordering = ['-created_at']
        permissions = [
            ('can_submit_report', 'Can submit reports'),
            ('can_review_report', 'Can review reports'),
        ]
    
    def __str__(self):
        return f"{self.get_report_type_display()}: {self.title} ({self.period_start} to {self.period_end})"
    
    def save(self, *args, **kwargs):
        # Update submitted_at when status changes to 'submitted'
        if self.status == 'submitted' and not self.submitted_at:
            self.submitted_at = timezone.now()
        
        # Update reviewed_at when status changes to 'reviewed', 'approved', or 'rejected'
        if self.status in ['reviewed', 'approved', 'rejected'] and not self.reviewed_at:
            self.reviewed_at = timezone.now()
            
        super().save(*args, **kwargs)
