# budgets/models.py
from django.db import models
from django.contrib.auth import get_user_model
from organisations.models import OrganisationBranch

User = get_user_model()

class Budget(models.Model):
    DRAFT = 'draft'
    PUBLISHED = 'published'
    STATUS_CHOICES = [
        (DRAFT, 'Draft'),
        (PUBLISHED, 'Published')
    ]

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='budgets')
    branch = models.ForeignKey(OrganisationBranch, on_delete=models.CASCADE, related_name='budgets', null=True, blank=True)
    financial_year = models.CharField(max_length=20)
    start_date = models.DateField()
    budget_period = models.CharField(max_length=20, default='Annual')
    usage_check = models.PositiveIntegerField(null=True, blank=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default=DRAFT)
    analysis_cache = models.JSONField(null=True, blank=True)
    analysis_cached_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.financial_year} ({self.budget_period}) - {self.status}"


class BudgetRow(models.Model):
    INCOME = 'income'
    EXPENSE = 'expense'
    TYPE_CHOICES = [
        (INCOME, 'Income'),
        (EXPENSE, 'Expense'),
    ]

    budget = models.ForeignKey(Budget, on_delete=models.CASCADE, related_name='rows')
    account_code = models.CharField(max_length=50)
    account_name = models.CharField(max_length=255)
    row_type = models.CharField(max_length=10, choices=TYPE_CHOICES)

    def __str__(self):
        return f"{self.account_name} ({self.row_type})"


class BudgetCell(models.Model):
    row = models.ForeignKey(BudgetRow, on_delete=models.CASCADE, related_name='cells')
    month = models.DateField()
    value = models.DecimalField(max_digits=15, decimal_places=2, default=0)

    class Meta:
        unique_together = ('row', 'month')
