from collections.abc import Iterator
from typing import Annotated

import psycopg
from fastapi import Depends
from src.__types.index import Tenant
from src.infrastructure.database.execute_tenant_rls import execute_tenant_rls
from src.routers.management.authorizer import get_tenant
from src.settings import Settings
from src.tracer import tracer

settings = Settings()


@tracer.capture_method
def get_connection(tenant: Annotated[Tenant, Depends(get_tenant)]) -> Iterator[psycopg.Connection]:
    # 処理終了時に接続を自動的にクローズする
    with psycopg.connect(conninfo=settings.postgres_url) as connection:
        # 全てのトランザクションを自動コミットする
        connection.autocommit = True
        # RLSでデータアクセスを制限するためにテナントIDを設定
        execute_tenant_rls(connection=connection, tenant_id=tenant.id)
        yield connection


@tracer.capture_method
def get_connection_without_tenant_scope() -> Iterator[psycopg.Connection]:
    """認証前エンドポイント用の接続。RLS用のtenant contextは設定しない。"""
    with psycopg.connect(conninfo=settings.postgres_url) as connection:
        connection.autocommit = True
        yield connection
