from decimal import Decimal

from django.db import models

from shop_management.models.data.shop import Shop
from shop_management.models.data.utils import Currency


class Account(models.Model):
    class AccountType(models.TextChoices):
        CASH = "CASH", "Cash"
        BANK = "BANK", "Bank"
        SARAFI = "SARAFI", "Sarafi"
        OTHER = "OTHER", "Other"
    """Cash/bank (or other) account per shop, with opening balance in one currency."""

    shop = models.ForeignKey(
        Shop, on_delete=models.CASCADE, related_name="accounts"
    )
    name = models.CharField(max_length=255)
    account_type = models.CharField(max_length=10, choices=AccountType.choices, default=AccountType.CASH)
    bank_name = models.CharField(max_length=255, blank=True)
    account_number = models.CharField(max_length=100, blank=True)
    sarafi_name = models.CharField(max_length=255, blank=True)
    is_active = models.BooleanField(default=True)
    is_system_account = models.BooleanField(
        default=False,
        help_text="Internal clearing account hidden from operational account lists and balances.",
    )
    allow_overdraft = models.BooleanField(
        default=False,
        help_text="Allow this account to go below zero when an authorized payment is posted.",
    )
    currency = models.ForeignKey(
        Currency, on_delete=models.CASCADE, related_name="accounts"
    )
    opening_balance = models.DecimalField(
        max_digits=14, decimal_places=2, default=Decimal("0")
    )
    note = models.TextField(blank=True, null=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["shop", "name"],
                name="unique_account_name_per_shop",
            )
        ]

    def __str__(self):
        return f"{self.name} ({self.shop})"
