from django.db import models


class SLAPolicy(models.Model):
    CATEGORY_CHOICES = [
        ('general',   'General Support'),
        ('billing',   'Billing'),
        ('technical', 'Technical'),
        ('complaint', 'Complaint'),
        ('hr',        'HR'),
        ('escalation','Escalation'),
        ('network',   'Network'),
        ('social',    'Social Media'),
    ]

    client = models.ForeignKey('clients.Client', on_delete=models.CASCADE, related_name='sla_policies')
    name = models.CharField(max_length=100)
    priority = models.CharField(max_length=10)
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='general')
    first_response_minutes = models.IntegerField(default=60)
    resolution_minutes = models.IntegerField(default=1440)
    escalation_minutes = models.IntegerField(default=120)
    warning_threshold_percent = models.IntegerField(default=80)
    business_hours_only = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.client.name} - {self.name} ({self.priority})"

    class Meta:
        verbose_name = 'SLA Policy'
        verbose_name_plural = 'SLA Policies'


class SLAPause(models.Model):
    ticket = models.ForeignKey('tickets.Ticket', on_delete=models.CASCADE, related_name='sla_pauses')
    paused_by = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True)
    reason = models.CharField(max_length=200)
    paused_at = models.DateTimeField(auto_now_add=True)
    resumed_at = models.DateTimeField(null=True, blank=True)
    duration_minutes = models.IntegerField(default=0)


class SLABreachLog(models.Model):
    FIRST_RESPONSE = 'first_response'
    RESOLUTION = 'resolution'

    TYPE_CHOICES = [
        (FIRST_RESPONSE, 'First Response'),
        (RESOLUTION, 'Resolution'),
    ]

    ticket = models.ForeignKey('tickets.Ticket', on_delete=models.CASCADE, related_name='sla_breaches')
    breach_type = models.CharField(max_length=20, choices=TYPE_CHOICES)
    breach_reason = models.TextField(blank=True)
    breached_at = models.DateTimeField(auto_now_add=True)
    minutes_overdue = models.IntegerField(default=0)
    notified = models.BooleanField(default=False)

    class Meta:
        ordering = ['-breached_at']


class BusinessHour(models.Model):
    DAYS = [
        (0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'),
        (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday'),
    ]

    client = models.ForeignKey('clients.Client', on_delete=models.CASCADE, related_name='business_hours')
    day_of_week = models.IntegerField(choices=DAYS)
    start_time = models.TimeField()
    end_time = models.TimeField()
    is_active = models.BooleanField(default=True)

    class Meta:
        unique_together = ['client', 'day_of_week']
