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


class Account(models.Model):
    TYPE_CHOICES = [
        ('cash', 'Cash'),
        ('bank', 'Bank'),
        ('wallet', 'Wallet'),
        ('receivable', 'Receivable'),
        ('payable', 'Payable'),
        ('other', 'Other'),
    ]

    name = models.CharField(max_length=150)
    type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='cash')
    opening_balance = models.DecimalField(max_digits=18, decimal_places=2, default=0)
    description = models.CharField(max_length=500, blank=True, default='')
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

    @property
    def balance(self):
        income = self.transactions.filter(transaction_type='income').aggregate(
            total=models.Sum('amount'))['total'] or 0
        expense = self.transactions.filter(transaction_type='expense').aggregate(
            total=models.Sum('amount'))['total'] or 0
        return self.opening_balance + income - expense


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

    account = models.ForeignKey(
        Account,
        on_delete=models.PROTECT,
        related_name='transactions'
    )
    transaction_type = models.CharField(max_length=10, choices=TYPE_CHOICES)
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    description = models.CharField(max_length=500, blank=True, default='')
    transaction_date = models.DateField()
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        related_name='accounting_transactions'
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-transaction_date', '-id')

    def __str__(self):
        return f'{self.get_transaction_type_display()} - {self.amount}'
