from django.db import models
from django.utils import timezone

class Job(models.Model):
    STATUS_CHOICES = [
        ('draft', 'Draft'),
        ('active', 'Active'),
        ('completed', 'Completed'),
        ('cancelled', 'Cancelled'),
    ]

    job_number = models.CharField(max_length=20, unique=True, editable=False)
    client_name = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        if not self.job_number:
            last_job = Job.objects.order_by('-id').first()
            if last_job and last_job.job_number.startswith('AIS'):
                try:
                    last_num = int(last_job.job_number[3:])
                    new_num = last_num + 1
                except ValueError:
                    new_num = 1
            else:
                new_num = 1
            self.job_number = f"AIS{new_num:04d}"
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.job_number} - {self.client_name}"

class Agreement(models.Model):
    job = models.OneToOneField(Job, on_delete=models.CASCADE, related_name='agreement')
    agreement_date = models.DateField(default=timezone.now)
    terms = models.TextField()
    scope_of_work = models.TextField()
    total_value = models.DecimalField(max_digits=12, decimal_places=2, default=0.00)
    
    def __str__(self):
        return f"Agreement for {self.job.job_number}"