from shop_management.models.base import DataRoot, models
from shop_management.models.data.shop_account import Account
from shop_management.models.data.utils import Currency
from shop_management.models.data.shop import Shop
from django.utils import timezone


class ExpenseCategory(DataRoot):
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name='expense_categories', null=True, blank=True)
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name


class Expense(DataRoot):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        POSTED = "POSTED", "Posted"
        VOID = "VOID", "Cancelled"

    expense_number = models.CharField(max_length=40, unique=True, null=True, blank=True)
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name='expenses', null=True, blank=True)
    category = models.ForeignKey(ExpenseCategory, on_delete=models.SET_NULL, null=True, blank=True, related_name='expenses')
    account = models.ForeignKey(
        Account,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="expenses",
    )
    expense_by = models.CharField(max_length=200)
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    currency = models.ForeignKey(Currency, on_delete=models.SET_NULL, null=True, blank=True)
    exchange_rate = models.DecimalField(max_digits=20, decimal_places=6, default=1)
    converted_amount = models.DecimalField(max_digits=18, decimal_places=2, default=0)
    payment_date = models.DateTimeField(default=timezone.now)
    notes = models.TextField(blank=True, null=True)
    attachment = models.FileField(upload_to="expenses/%Y/%m/", blank=True, null=True)
    status = models.CharField(max_length=10, choices=Status.choices, default=Status.DRAFT)
    posted_at = models.DateTimeField(null=True, blank=True)
    posted_by = models.ForeignKey(
        "account.User", null=True, blank=True, on_delete=models.PROTECT,
        related_name="expenses_posted",
    )
    voided_at = models.DateTimeField(null=True, blank=True)
    voided_by = models.ForeignKey(
        "account.User", null=True, blank=True, on_delete=models.PROTECT,
        related_name="expenses_voided",
    )
    void_reason = models.TextField(blank=True)

    class Meta:
        ordering = ["-payment_date", "-id"]

    @property
    def financial_account(self):
        return self.account

    @property
    def exchange_rate_used(self):
        return self.exchange_rate

    @property
    def base_amount(self):
        return self.converted_amount

    @property
    def expense_date(self):
        return self.payment_date.date() if self.payment_date else None

    @property
    def description(self):
        return self.notes

    def __str__(self):
        return f"{self.expense_by} - {self.amount}"
