# retoor <retoor@molodetz.nl>

import io
import re
import uuid
import requests
from PIL import Image
from tests.conftest import BASE_URL
def _user_uploads(prefix="up"):
    s = requests.Session()
    name = f"{prefix}_{uuid.uuid4().hex[:10]}"
    s.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@test.dev",
            "password": "secret123",
            "confirm_password": "secret123",
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    return s, name
def _session_uploads():
    s, _ = _user_uploads()
    return s
def _png_bytes_uploads():
    buf = io.BytesIO()
    Image.new("RGB", (4, 4), (255, 0, 0)).save(buf, "PNG")
    return buf.getvalue()
def _upload_uploads(s, name="a.png"):
    r = s.post(
        f"{BASE_URL}/uploads/upload", files={"file": (name, _png_bytes_uploads(), "image/png")}
    )
    assert r.status_code == 201, r.text
    return r.json()["uid"]


def test_message_links_multiple_attachments(app_server):
    alice = _session_uploads()
    bob, bob_name = _user_uploads("bob")
    found = alice.get(f"{BASE_URL}/messages/search", params={"q": bob_name}).json()[
        "results"
    ]
    bob_uid = found[0]["uid"]

    u1, u2 = _upload_uploads(alice), _upload_uploads(alice)
    r = alice.post(
        f"{BASE_URL}/messages/send",
        data={
            "content": "Message with attachments",
            "receiver_uid": bob_uid,
            "attachment_uids": f"{u1},{u2}",
        },
        allow_redirects=True,
    )
    assert r.status_code == 200, r.text[:300]
    assert u1 in r.text and u2 in r.text, (
        "both attachments must be linked and displayed in the conversation"
    )
