from django.db import models

from apps.core.models import Currency, TimeStampedModel


class TransactionType(models.TextChoices):
    CAPITAL = "capital", "Capital contribution"
    BENEFIT = "benefit", "Benefit distribution"
    REFUND = "refund", "Refund"
    FEE = "fee", "Fee"
    ADJUSTMENT = "adjustment", "Adjustment"


class TransactionStatus(models.TextChoices):
    PENDING = "pending", "Pending"
    POSTED = "posted", "Posted"
    FAILED = "failed", "Failed"
    REVERSED = "reversed", "Reversed"


class Transaction(TimeStampedModel):
    reference = models.CharField(max_length=40, unique=True)
    investor = models.ForeignKey("investors.Investor", on_delete=models.CASCADE, related_name="transactions")
    investment = models.ForeignKey(
        "investments.Investment",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="transactions",
    )
    project = models.ForeignKey("projects.Project", null=True, blank=True, on_delete=models.SET_NULL, related_name="transactions")
    txn_type = models.CharField(max_length=20, choices=TransactionType.choices)
    status = models.CharField(max_length=20, choices=TransactionStatus.choices, default=TransactionStatus.POSTED)
    currency = models.CharField(max_length=8, choices=Currency.choices, default=Currency.BDT)
    amount = models.DecimalField(max_digits=16, decimal_places=2)
    occurred_on = models.DateField()
    description = models.CharField(max_length=255, blank=True)
    posted_by = models.ForeignKey(
        "accounts.User",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="posted_transactions",
    )

    class Meta:
        ordering = ["-occurred_on", "-id"]

    def __str__(self):
        return f"{self.reference} · {self.amount}"
