import inject
from litestar import Controller, get
from litestar.exceptions import HTTPException
from litestar.response import Response

from server.modules.attachments import AtachmentService


class AtachmentController(Controller):
    @get("/attachments/{raw_path:path}", media_type="image/jpeg")
    async def get_file(self, raw_path: str) -> Response:
        attach_service: AtachmentService = inject.instance(AtachmentService)

        attach_path = attach_service.path_from_url(raw_path)
        # Query within session scope
        attach = await attach_service.get_info_bypath(session=None, path=[attach_path])
        if not attach:
            raise HTTPException(status_code=404, detail="Attachment not found")

        # Get file data (assuming async)
        body = await attach_service.get_data(attach_path)

        # Extract metadata within session scope
        content_type = attach[0].content_type
        last_mod = attach[0].created_at.strftime("%a, %d %b %Y %H:%M:%S GMT")

        return Response(
            content=body,
            media_type=content_type,
            headers={
                "Cache-Control": "public, max-age=864000",
                "Last-Modified": last_mod,
            },
        )
