from __future__ import annotations

import json

import pytest
from fastapi import HTTPException

from app.models.admin import Admin, Role
from app.services.admin_permission_service import ALL_PERMISSION_CODES, permissions_for, require_permission


def test_super_admin_has_all_permissions() -> None:
    admin = Admin(id=1, username="root", password="unused", name="root", status=1, is_super_admin=1)
    assert permissions_for(admin) == ALL_PERMISSION_CODES


def test_role_permissions_are_restricted_to_catalog() -> None:
    role = Role(code="operator", name="operator", permissions=json.dumps(["users.view", "unknown.permission"]))
    admin = Admin(id=2, username="operator", password="hash", name="operator", status=1, is_super_admin=0, role=role)
    assert permissions_for(admin) == {"users.view"}
    require_permission(admin, "users.view")
    with pytest.raises(HTTPException) as exc:
        require_permission(admin, "users.delete")
    assert exc.value.status_code == 403
