# reports/models.py
"""
Models for storing and managing generated reports.
"""
from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class SavedReport(models.Model):
    """
    Stores generated reports for later access and reference.
    
    This model saves reports that have been generated so they can be
    accessed again without regenerating. Reports can be of different types
    (academic, attendance, financial) and store the parameters used to
    generate them.
    
    Attributes:
        title (str): Descriptive title of the report
        report_type (str): Type of report from REPORT_TYPES choices
        generated_by (ForeignKey): User who generated the report
        generated_at (datetime): Timestamp when report was generated
        file (FileField): The actual report file (PDF, Excel, etc.)
        parameters (JSONField): JSON object containing generation parameters
            (date ranges, class filters, etc.)
    """
    
    REPORT_TYPES = [
        ('academic', 'Academic Report'),
        ('attendance', 'Attendance Report'),
        ('financial', 'Financial Report'),
    ]
    
    title = models.CharField(
        max_length=200
    )
    report_type = models.CharField(
        max_length=20, 
        choices=REPORT_TYPES
    )
    generated_by = models.ForeignKey(
        User, 
        on_delete=models.CASCADE
    )
    generated_at = models.DateTimeField(
        auto_now_add=True
    )
    file = models.FileField(
        upload_to='reports/'
    )
    parameters = models.JSONField(
        default=dict
    )
    
    class Meta:
        verbose_name = "Saved Report"
        verbose_name_plural = "Saved Reports"
        ordering = ['-generated_at']
        indexes = [
            models.Index(fields=['report_type']),
            models.Index(fields=['generated_at']),
        ]
    
    def __str__(self):
        """Return string representation of the saved report."""
        return f"{self.title} - {self.generated_at.date()}"
    
    def get_parameters_display(self):
        """
        Get a human-readable representation of the report parameters.
        
        Returns:
            str: Formatted string showing the key parameters used.
        """
        if not self.parameters:
            return "No parameters"
        
        param_strings = []
        for key, value in self.parameters.items():
            param_strings.append(f"{key.replace('_', ' ').title()}: {value}")
        
        return ", ".join(param_strings)