from datetime import datetime
from typing import Literal

from tortoise import fields
from tortoise.models import Model
from tortoise.validators import MinLengthValidator

from service.core.security import get_password_hash
from service.database.validators import EmailValidator

__all__ = [
    "User",
    "AnonymousUser",
]


class TimestampMixin(Model):
    id: int = fields.BigIntField(pk=True)
    created_at: datetime = fields.DatetimeField(null=True, auto_now_add=True)
    modified_at: datetime = fields.DatetimeField(null=True, auto_now=True)

    class Meta:
        abstract = True


class User(TimestampMixin, Model):
    email = fields.CharField(max_length=255, validators=[MinLengthValidator(5), EmailValidator(False)], unique=True)
    username = fields.CharField(max_length=32, unique=True)
    password = fields.CharField(max_length=256)
    is_superuser = fields.BooleanField(default=False, description="Is user a SuperUser?")

    # Helper for auto-complete and typing
    # model_set: fields.ReverseRelation["DatabaseModel"]

    def set_password(self, new_password: str) -> None:
        self.password = get_password_hash(new_password)


class AnonymousUser:
    id: Literal[0] = 0
    email: Literal[""] = ""
    username: Literal[""] = ""
