from contextlib import asynccontextmanager
from pathlib import Path
from tempfile import TemporaryDirectory

import pytest

from konabot.common.database import DatabaseManager
from konabot.common.permsys import PermManager, register_default_allow_permission
from konabot.common.permsys.entity import PermEntity
from konabot.common.permsys.migrates import execute_migration


@asynccontextmanager
async def tempdb():
    with TemporaryDirectory() as _tempdir:
        tempdir = Path(_tempdir)
        db = DatabaseManager(tempdir / "perm.sqlite3")
        yield db
        await db.close_all_connections()


@pytest.mark.asyncio
async def test_register_default_allow_permission_records_key():
    register_default_allow_permission("test.default.allow")

    async with tempdb() as db:
        async with db.get_conn() as conn:
            await execute_migration(conn)

        pm = PermManager(db)
        await pm.update_permission(
            PermEntity("sys", "global", "global"),
            "test.default.allow",
            True,
        )

        assert await pm.check_has_permission(
            [PermEntity("dummy", "user", "1"), PermEntity("sys", "global", "global")],
            "test.default.allow.sub",
        )
