"""Organization middleware.

⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT

Provides FastAPI dependencies for organization-scoped access control.
"""

from __future__ import annotations

import logging

from fastapi import HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from {{ project_name }}.organization.org_membership_model import OrganizationMembership
from {{ project_name }}.organization.org_service import get_membership, has_org_permission

logger = logging.getLogger(__name__)


async def get_org_membership(
    db: AsyncSession,
    org_id: int,
    user_id: int,
) -> OrganizationMembership:
    """Get a user's active membership in an organization.

    Raises 403 if the user is not a member.
    """
    membership = await get_membership(db, org_id, user_id)
    if not membership or not membership.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not a member of this organization",
        )
    return membership


def require_org_permission(
    membership: OrganizationMembership,
    permission: str,
) -> None:
    """Check that a membership has the required permission.

    Raises 403 if the member's role does not include the permission.
    """
    if not has_org_permission(membership.role, permission):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=f"Insufficient organization permissions. Required: {permission}",
        )
