from django.db import models
from django.core.validators import MinValueValidator
from django.conf import settings
from organisations.models import Organisation
from ledgers.models import OrganisationSubAccount


class MobileMoneySettings(models.Model):
    """
    Organization-level mobile money transaction charges configuration.
    Settings apply to the entire organization and are not branch-specific.
    """
    CHARGE_TYPE_CHOICES = [
        ('fixed', 'Fixed Amount'),
        ('percentage', 'Percentage'),
    ]

    SETTING_TYPE_CHOICES = [
        ('deposit', 'Deposit'),
        ('withdrawal', 'Withdrawal'),
    ]

    organization = models.ForeignKey(
        Organisation,
        on_delete=models.CASCADE,
        related_name='mobile_money_settings'
    )

    # Setting type: deposit or withdrawal
    setting_type = models.CharField(
        max_length=20,
        choices=SETTING_TYPE_CHOICES
    )

    # Charge configuration
    charge_amount = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
        validators=[MinValueValidator(0)],
        help_text="Charge amount for this setting"
    )
    charge_type = models.CharField(
        max_length=20,
        choices=CHARGE_TYPE_CHOICES,
        default='fixed'
    )

    income_account = models.ForeignKey(
        OrganisationSubAccount,
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name='mobile_money_charges',
        help_text="Income account where transaction charges are posted"
    )

    # Status and metadata
    is_active = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        related_name='mobile_money_settings_created'
    )

    class Meta:
        db_table = 'mobile_money_settings'
        unique_together = ('organization', 'setting_type')

    def __str__(self):
        return f"{self.setting_type.title()} - {self.organization.name}"

    def calculate_charge(self, amount):
        """Calculate charge based on configuration"""
        if self.charge_type == 'percentage':
            return (amount * self.charge_amount) / 100
        return self.charge_amount
