from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from app.api.dependencies import ServiceContainer, get_db
from app.api import schemas

def create_documents_router(services: ServiceContainer) -> APIRouter:
    router = APIRouter(prefix="/documents", tags=["Documents"])

    @router.post("/", response_model=schemas.DocumentResponse, summary="Add a New Document")
    def add_document(doc: schemas.DocumentCreate, db: Session = Depends(get_db)):
        try:
            doc_data = doc.model_dump()
            document_id = services.document_service.add_document(db=db, doc_data=doc_data)
            return schemas.DocumentResponse(
                message=f"Document '{doc.title}' added successfully with ID {document_id}"
            )
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"An error occurred: {e}")

    @router.get("/", response_model=schemas.DocumentListResponse, summary="List All Documents")
    def get_documents(db: Session = Depends(get_db)):
        try:
            documents_from_db = services.document_service.get_all_documents(db=db)
            return {"documents": documents_from_db}
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"An error occurred: {e}")

    @router.delete("/{document_id}", response_model=schemas.DocumentDeleteResponse, summary="Delete a Document")
    def delete_document(document_id: int, db: Session = Depends(get_db)):
        try:
            deleted_id = services.document_service.delete_document(db=db, document_id=document_id)
            if deleted_id is None:
                raise HTTPException(status_code=404, detail=f"Document with ID {document_id} not found.")

            return schemas.DocumentDeleteResponse(
                message="Document deleted successfully",
                document_id=deleted_id
            )
        except HTTPException:
            raise
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
    
    return router