import uuid
from gvsdsdk.auth.cookie import ELT_COOKIE_NAME


class ELTAuthentication:
    def authenticate(self, request):
        elt_token = request.COOKIES.get(ELT_COOKIE_NAME)
        if not elt_token:
            return None

        try:
            token_uuid = uuid.UUID(elt_token)
        except (ValueError, AttributeError):
            return None

        from gvsdsdk.models import EphemeralToken
        from gvsds.apps.core.models import User
        import datetime

        try:
            elt = EphemeralToken.objects.get(
                ELTUUID=token_uuid,
                ELTStatus=1,
            )
        except EphemeralToken.DoesNotExist:
            return None

        now_utc = datetime.datetime.now(datetime.timezone.utc)
        if elt.ELTEndTime.replace(tzinfo=None) < now_utc.replace(tzinfo=None):
            return None

        # 滑动续期：剩余时间不足7天时，延长30天
        remaining = elt.ELTEndTime.replace(tzinfo=None) - now_utc.replace(tzinfo=None)
        if remaining < datetime.timedelta(days=7):
            elt.ELTEndTime = now_utc + datetime.timedelta(days=30)
            elt.save(update_fields=['ELTEndTime'])

        try:
            user = User.objects.get(UserUUID=elt.ELTUserUUID)
        except User.DoesNotExist:
            return None

        request.elt = elt
        return (user, elt_token)

    def authenticate_header(self, request):
        return 'Bearer'
