"""Attachment download: streams a preserved non-art post file."""

from quart import Blueprint, jsonify, send_file

from ..extensions import get_session
from ..models import PostAttachment

attachments_bp = Blueprint(
    "attachments", __name__, url_prefix="/api/attachments"
)


@attachments_bp.route("/<int:attachment_id>/download", methods=["GET"])
async def download(attachment_id: int):
    async with get_session() as session:
        att = await session.get(PostAttachment, attachment_id)
        if att is None:
            return jsonify({"error": "not found"}), 404
        path = att.path
        filename = att.original_filename
        mimetype = att.mime or "application/octet-stream"
    return await send_file(
        path,
        mimetype=mimetype,
        as_attachment=True,
        attachment_filename=filename,
    )
