import uuid

from django.contrib.auth.models import AbstractUser
from django.db import models

from apps.common.models import TimeStampedModel


class User(AbstractUser):
    class Status(models.TextChoices):
        ACTIVE = "active", "Active"
        DISABLED = "disabled", "Disabled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.ACTIVE)
    phone = models.CharField(max_length=32, blank=True)
    avatar_url = models.URLField(blank=True)

    @property
    def is_disabled(self) -> bool:
        return self.status == self.Status.DISABLED


class Team(TimeStampedModel):
    class Status(models.TextChoices):
        ACTIVE = "active", "Active"
        DISABLED = "disabled", "Disabled"

    name = models.CharField(max_length=128)
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.ACTIVE)
    owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name="owned_teams")

    def __str__(self) -> str:
        return self.name


class TeamMember(TimeStampedModel):
    class Role(models.TextChoices):
        OWNER = "owner", "Owner"
        ADMIN = "admin", "Admin"
        MEMBER = "member", "Member"
        VIEWER = "viewer", "Viewer"

    class Status(models.TextChoices):
        ACTIVE = "active", "Active"
        INVITED = "invited", "Invited"
        DISABLED = "disabled", "Disabled"

    team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="members")
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="team_memberships")
    role = models.CharField(max_length=24, choices=Role.choices, default=Role.MEMBER)
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.ACTIVE)
    monthly_credit_limit = models.DecimalField(max_digits=12, decimal_places=2, default=0)

    class Meta:
        unique_together = [("team", "user")]

    def __str__(self) -> str:
        return f"{self.team} / {self.user} / {self.role}"
