"""Policy interface for row-level authorization."""

from __future__ import annotations

from typing import Protocol, runtime_checkable

from pydantic import BaseModel
from sqlmodel import SQLModel

from auen.types import SelectQuery, User


@runtime_checkable
class CrudPolicy(Protocol):
    """Protocol for CRUD authorization policies.

    Implement this to control who can access which rows.
    The ``filter_list_query`` method is critical to prevent
    data leaks on LIST endpoints.
    """

    def can_create(self, user: User, obj_in: BaseModel) -> bool: ...

    def can_read(self, user: User, db_obj: SQLModel) -> bool: ...

    def can_update(self, user: User, db_obj: SQLModel, obj_in: BaseModel) -> bool: ...

    def can_delete(self, user: User, db_obj: SQLModel) -> bool: ...

    def filter_list_query(
        self, user: User, query: SelectQuery[SQLModel]
    ) -> SelectQuery[SQLModel]: ...


class AllowAll:
    """Default policy that allows everything."""

    def can_create(self, user: User, obj_in: BaseModel) -> bool:
        return True

    def can_read(self, user: User, db_obj: SQLModel) -> bool:
        return True

    def can_update(self, user: User, db_obj: SQLModel, obj_in: BaseModel) -> bool:
        return True

    def can_delete(self, user: User, db_obj: SQLModel) -> bool:
        return True

    def filter_list_query(
        self, user: User, query: SelectQuery[SQLModel]
    ) -> SelectQuery[SQLModel]:
        return query
