import sqlalchemy
from sqlalchemy import DDL, event

from openlog.datamodel.connection.sqlalchemy.sqlalchemy_imports_interface import (
    SqlAlchemyImportsInterface,
)


class XplordbImportsInterface(SqlAlchemyImportsInterface):
    def _before_sqlalchemy_table_creation(
        self, table: sqlalchemy.Table, schema: str
    ) -> None:
        """
        Define sqlalchemy events before table creation. Used to define specific permission on created table.

        Args:
            base: sqlalchemy base to be created
            schema: (str) database schema used
        """
        schema_str = ""
        if schema:
            schema_str = schema + "."

        event.listen(
            table,
            "after_create",
            DDL(
                f"ALTER TABLE {schema_str}{table.name} OWNER TO xdb_admin;"
                f"GRANT SELECT, TRIGGER ON TABLE {schema_str}{table.name} TO xdb_viewer;"
                f"GRANT SELECT, UPDATE, INSERT, TRIGGER ON TABLE {schema_str}{table.name} TO xdb_logger;"
                f"GRANT ALL ON TABLE {schema_str}{table.name} TO xdb_admin;"
            ),
        )
