from django.db import models


class ApprovalRequest(models.Model):
    PENDING = 'pending'
    APPROVED = 'approved'
    REJECTED = 'rejected'
    RETURNED = 'returned'
    ESCALATED = 'escalated'
    EXPIRED = 'expired'

    STATUS_CHOICES = [
        (PENDING, 'Pending'),
        (APPROVED, 'Approved'),
        (REJECTED, 'Rejected'),
        (RETURNED, 'Returned for Correction'),
        (ESCALATED, 'Escalated'),
        (EXPIRED, 'Expired'),
    ]

    TYPE_CHOICES = [
        ('refund', 'Refund Approval'),
        ('billing_correction', 'Billing Correction'),
        ('technical_escalation', 'Technical Escalation'),
        ('service_adjustment', 'Service Adjustment'),
        ('compensation', 'Complaint Compensation'),
        ('account_modification', 'Account Modification'),
        ('closure', 'Ticket Closure'),
        ('other', 'Other'),
    ]

    ticket = models.ForeignKey('tickets.Ticket', on_delete=models.CASCADE, related_name='approval_requests')
    approval_type = models.CharField(max_length=30, choices=TYPE_CHOICES)
    title = models.CharField(max_length=200)
    description = models.TextField()
    amount = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=PENDING)
    requested_by = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, related_name='approval_requests_sent')
    current_approver = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True, related_name='pending_approvals')
    deadline = models.DateTimeField(null=True, blank=True)
    reminder_sent = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.title} - {self.ticket.ticket_number}"


class ApprovalLevel(models.Model):
    approval_request = models.ForeignKey(ApprovalRequest, on_delete=models.CASCADE, related_name='levels')
    level = models.IntegerField()
    approver = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True)
    status = models.CharField(max_length=20, default='pending')
    comments = models.TextField(blank=True)
    decided_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['level']


class ApprovalAttachment(models.Model):
    approval = models.ForeignKey(ApprovalRequest, on_delete=models.CASCADE, related_name='attachments')
    file = models.FileField(upload_to='approval_attachments/')
    filename = models.CharField(max_length=255)
    uploaded_by = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
