"""
Author: Michel Peltriaux
Created on: 10.05.26

"""
from django.db import models


class ExternalIdentifier(models.Model):
    """ Holds a lookup to match a given external identifier against the internal identifier in konova.

    Relevant in cases of API transmitted entries, which are updates using external identifiers instead of
    the internal ones directly.

    """
    external_id = models.CharField(
        max_length=255,
        primary_key=True,
        db_comment="Identifier from a source system"
    )
    internal_id = models.UUIDField(
        db_comment="Identifier in konova"
    )
    created = models.ForeignKey(
        "user.UserActionLogEntry",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='+'
    )

    def __str__(self):
        return f"{self.external_id} -> {self.internal_id}"

    @staticmethod
    def resolve_external_identifier(external_identifier: str):
        """ Returns a ExternalIdentifier object, if the given parameter could be resolved as an external identifier.

        Args:
            external_identifier (str): An external identifier.

        Returns:
            ExternalIdentifier | None
        """
        if external_identifier:
            try:
                obj = ExternalIdentifier.objects.get(external_id=external_identifier)
                return obj
            except ExternalIdentifier.DoesNotExist:
                pass
        return None
