"""Model fields: ``UUIDv7Field`` with a portable column type (TZ 2.2.1 p.3)."""

from __future__ import annotations

import uuid
from typing import Any

from django.db import models

from .ids import uuid7


class UUIDv7Field(models.UUIDField):
    """UUID primary/foreign key generated by the application (no DB-side default).

    PostgreSQL: native ``uuid``. MySQL/MariaDB: always ``char(32) ascii_bin`` (MariaDB 10.7+ native
    UUID type has a non-bytewise sort order), lowercase hex without dashes.
    """

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        if kwargs.get("primary_key"):
            kwargs.setdefault("default", uuid7)
            kwargs.setdefault("editable", False)
        super().__init__(*args, **kwargs)

    def deconstruct(self) -> tuple[Any, ...]:
        name, path, args, kwargs = super().deconstruct()
        return name, path, args, kwargs

    def db_type(self, connection: Any) -> str | None:
        if connection.vendor == "mysql":
            return "char(32) CHARACTER SET ascii COLLATE ascii_bin"
        return super().db_type(connection)

    def rel_db_type(self, connection: Any) -> str | None:
        return self.db_type(connection)

    def get_db_prep_value(self, value: Any, connection: Any, prepared: bool = False) -> Any:
        if connection.vendor == "mysql":
            if value is None:
                return None
            if not isinstance(value, uuid.UUID):
                value = self.to_python(value)
            return value.hex
        return super().get_db_prep_value(value, connection, prepared)
