import math
import time
from typing import TYPE_CHECKING

from django.contrib import admin as django_admin
from django.contrib.admin.exceptions import AlreadyRegistered  # type: ignore
from django.contrib.auth.models import User
from django.db import models


class tUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)

    if TYPE_CHECKING:
        sessions = models.Manager["tSession"]

    def __str__(self) -> str:
        return self.user.username

class tSession(models.Model):
    u_for = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sessions")
    session_id = models.CharField(max_length=128, unique=True, primary_key=True)
    last_use = models.IntegerField()
    created = models.IntegerField()

    def register_usage(self):
        self.last_use = math.floor(time.time())
        self.save(update_fields=["last_use"])

    def __str__(self) -> str:
        return f"{self.u_for.username} - created: {self.created} - last usage: {self.last_use}"

try:
    django_admin.site.register((tUser, tSession))
except AlreadyRegistered:
    ...
