import uuid
from datetime import datetime, timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

from app.domain.models import DocumentCreateRequest, DocumentCreatedResponse
from app.adapters import storage, routing
from app.adapters.orm import Document

DEFAULT_GRACE_PERIOD_DAYS = 90

async def create_document(
    req: DocumentCreateRequest,
    session: AsyncSession,
) -> DocumentCreatedResponse:
    storage_key = await storage.save_encrypted_payload(req.encryptedPayload)
    assigned_unit = await routing.route_document(req.metadata)
    retention_date = datetime.utcnow() + timedelta(days=DEFAULT_GRACE_PERIOD_DAYS)

    doc = Document(
        reference_number=req.metadata.referenceNumber,
        authority_id=req.metadata.authorityId,
        status="ROUTED",
        assigned_unit=assigned_unit,
        storage_path=storage_key,
        retention_date=retention_date,
        personal_archive=False,
    )
    session.add(doc)
    await session.commit()
    await session.refresh(doc)

    return DocumentCreatedResponse(
        id=str(doc.id),
        status=doc.status,
        assignedUnit=doc.assigned_unit,
    )

async def get_document(doc_id: uuid.UUID, session: AsyncSession) -> Document | None:
    stmt = select(Document).where(Document.id == doc_id)
    res = await session.execute(stmt)
    return res.scalar_one_or_none()
