import uuid

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

from core.models import Project, TimeStampedModel


class Member(TimeStampedModel):
    """A partner in the joint construction project."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    project = models.ForeignKey(
        Project, on_delete=models.DO_NOTHING, related_name="members",
        db_constraint=False,  # Project lives in the shared platform DB, not this company DB
    )
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
        related_name="member_profile",
        help_text="Link to a login account so this member can see their own ledger.",
        db_constraint=False,  # CustomUser lives in the shared platform DB, not this company DB
    )
    full_name = models.CharField(max_length=255)
    mobile_number = models.CharField(max_length=20)
    email = models.EmailField(blank=True)
    address = models.TextField(blank=True)
    nid_number = models.CharField("NID No.", max_length=50, blank=True)
    tin_number = models.CharField("TIN No.", max_length=50, blank=True)
    present_address = models.TextField(blank=True)
    permanent_address = models.TextField(blank=True)
    photo = models.ImageField(upload_to="member_photos/", null=True, blank=True)

    share_percent = models.DecimalField(
        max_digits=5, decimal_places=2, default=0,
        help_text="This member's ownership share of the project, in %.",
    )
    committed_amount = models.DecimalField(
        "Total Commitment (৳)",
        max_digits=14, decimal_places=2, default=0,
        help_text="The total amount this member has committed to contribute to the project.",
    )
    starting_balance = models.DecimalField(
        max_digits=14, decimal_places=2, default=0,
        help_text="Opening balance already standing for this member when the member is added.",
    )
    join_date = models.DateField(null=True, blank=True)
    is_active = models.BooleanField(default=True)
    notes = models.TextField(blank=True)

    class Meta:
        db_table = "members_member"
        ordering = ["full_name"]
        unique_together = ["project", "mobile_number"]

    def __str__(self):
        return self.full_name

    def clean(self):
        # Project is stored as an ID because Project itself lives in the shared
        # platform database. Do not dereference project here.
        from django.core.exceptions import ValidationError
        if self.project_id and self.mobile_number:
            qs = type(self).objects.filter(
                project_id=self.project_id,
                mobile_number=self.mobile_number.strip(),
            )
            if self.pk:
                qs = qs.exclude(pk=self.pk)
            if qs.exists():
                raise ValidationError({
                    "mobile_number": "A member with this mobile number already exists in this company."
                })

    @property
    def total_paid(self):
        return self.contributions.aggregate(total=models.Sum("amount"))["total"] or 0

    @property
    def current_balance(self):
        """Opening balance plus all deposit/contribution receipts."""
        return self.starting_balance + self.total_paid

    @property
    def surplus_deficit(self):
        """(Starting Balance + Total Deposits) - Total Commitment.
        Positive = Surplus (contributed more than committed).
        Negative = Deficit (still owes against their commitment)."""
        return self.current_balance - self.committed_amount

    @property
    def surplus_amount(self):
        return max(self.surplus_deficit, 0)

    @property
    def due_amount(self):
        """Deficit against commitment — kept as `due_amount` for backward
        compatibility with existing reports/templates. Always >= 0."""
        return max(-self.surplus_deficit, 0)
