"""Document service for managing document records."""

from typing import Optional
from uuid import UUID

import structlog
from sqlalchemy.ext.asyncio import AsyncSession

from src.db.models import Document

logger = structlog.get_logger(__name__)


async def create_document(
    filename: str,
    file_path: str,
    file_size: int,
    api_key_id: UUID,
    session: AsyncSession,
    tenant_id: Optional[UUID] = None,
    node_id: Optional[UUID] = None,
) -> Document:
    """Create a new document record in the database.

    Initial status is set to "pending" for async processing.

    Args:
        filename: Original filename of the uploaded file.
        file_path: Storage path where file was saved.
        file_size: Size of the file in bytes.
        api_key_id: UUID of the API key used for authentication.
        session: Async database session.
        tenant_id: Tenant UUID for data isolation.
        node_id: Node UUID for data isolation.

    Returns:
        The created Document model.
    """
    document = Document(
        filename=filename,
        file_path=file_path,
        file_size_bytes=file_size,
        status="pending",
        api_key_id=api_key_id,
        tenant_id=tenant_id,
        node_id=node_id,
    )

    # Set RLS tenant context for row-level security policy
    if tenant_id:
        from sqlalchemy import text
        from uuid import UUID as _UUID
        _tid = str(_UUID(str(tenant_id)))  # validate UUID format
        await session.execute(text(f"SET LOCAL app.tenant_id = '{_tid}'"))

    session.add(document)
    await session.commit()
    await session.refresh(document)

    logger.info(
        "document_created",
        document_id=str(document.id),
        filename=filename,
        file_size=file_size,
        status=document.status,
        api_key_id=str(api_key_id),
        tenant_id=str(tenant_id),
        node_id=str(node_id),
    )

    return document
