import dataclasses

import sqlalchemy.orm

from .entity_name_to_class import add_to_entity_name_to_class
from ..utils.text import camel_case_to_underscore


def sqlalchemy_dataclass(sqlalchemy_mapper_registry: sqlalchemy.orm.registry, table_name: str = None):
    def inner(class_: type):
        class_.__sa_dataclass_metadata_key__ = "sa"
        if table_name:
            class_.__tablename__ = table_name
        if not hasattr(class_, '__tablename__'):
            class_.__tablename__ = camel_case_to_underscore(class_.__name__)
        entity = dataclasses.dataclass(class_)
        add_to_entity_name_to_class(entity)
        return sqlalchemy_mapper_registry.mapped(entity)
    return inner
