from django.db import models
from django.conf import settings


class ApprovalFlow(models.Model):
    """
    Tracks the multi-stage approval pipeline for a cost sheet.
    Stages: TL Review → PM Review → CEO Decision
    """
    STAGE_CHOICES = [
        ('TL_Review', 'Team Lead Review'),
        ('PM_Review', 'Project Manager Review'),
        ('CEO_Decision', 'CEO Final Decision'),
    ]
    STATUS_CHOICES = [
        ('Pending', 'Pending'),
        ('Approved', 'Approved'),
        ('Rejected', 'Rejected'),
        ('Revised', 'Needs Revision'),
    ]

    cost_sheet = models.OneToOneField(
        'costing.CostSheet', on_delete=models.CASCADE, related_name='approval'
    )
    lead = models.ForeignKey(
        'leads.Lead', on_delete=models.CASCADE, related_name='approvals'
    )
    current_stage = models.CharField(max_length=20, choices=STAGE_CHOICES, default='TL_Review')
    overall_status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='Pending')

    submitted_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='submitted_approvals'
    )
    submitted_at = models.DateTimeField(auto_now_add=True)
    completed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['-submitted_at']

    def __str__(self):
        return f"Approval — {self.lead.title} (Stage: {self.current_stage})"

    @property
    def stage_index(self):
        stages = ['TL_Review', 'PM_Review', 'CEO_Decision']
        return stages.index(self.current_stage) if self.current_stage in stages else -1

    def advance_stage(self):
        """Move to the next approval stage."""
        stages = ['TL_Review', 'PM_Review', 'CEO_Decision']
        idx = stages.index(self.current_stage)
        if idx < len(stages) - 1:
            self.current_stage = stages[idx + 1]
            self.save()
            return True
        return False


class ApprovalAction(models.Model):
    """
    Immutable audit log for each approval action taken.
    """
    ACTION_CHOICES = [
        ('approve', 'Approved'),
        ('reject', 'Rejected'),
        ('revise', 'Sent for Revision'),
    ]

    approval = models.ForeignKey(ApprovalFlow, on_delete=models.CASCADE, related_name='actions')
    stage = models.CharField(max_length=20)
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    action = models.CharField(max_length=10, choices=ACTION_CHOICES)
    comment = models.TextField()  # Mandatory comment
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['timestamp']

    def __str__(self):
        return f"{self.get_action_display()} by {self.actor.full_name} at {self.stage}"
