from datetime import UTC, datetime

import pytest

from backend.app.models import (
    Artist,
    ImageProvenance,
    ImageRecord,
    Post,
    Source,
)

pytestmark = pytest.mark.integration


async def _seed_full(db):
    rec = ImageRecord(
        path="/images/p/1.jpg", sha256="p" + "0" * 63,
        size_bytes=1, mime="image/jpeg", width=1, height=1,
        origin="imported_filesystem", integrity_status="unknown",
    )
    artist = Artist(name="Alice", slug="alice")
    db.add_all([rec, artist])
    await db.flush()
    source = Source(artist_id=artist.id, platform="patreon",
                    url="https://patreon.test/alice")
    db.add(source)
    await db.flush()
    post = Post(source_id=source.id, artist_id=artist.id,
                external_post_id="555",
                post_url="https://patreon.test/p/555", post_title="Set 1",
                post_date=datetime(2023, 8, 1, tzinfo=UTC),
                description="<p>hi</p>", attachment_count=2)
    db.add(post)
    await db.flush()
    db.add(ImageProvenance(image_record_id=rec.id, post_id=post.id,
                           source_id=source.id))
    await db.flush()
    await db.commit()
    return rec.id, post.id


@pytest.mark.asyncio
async def test_image_provenance_endpoint(client, db):
    image_id, post_id = await _seed_full(db)
    resp = await client.get(f"/api/provenance/image/{image_id}")
    assert resp.status_code == 200
    body = await resp.get_json()
    assert body["image_id"] == image_id
    assert len(body["provenance"]) == 1
    assert body["provenance"][0]["post"]["id"] == post_id


@pytest.mark.asyncio
async def test_image_provenance_404(client):
    resp = await client.get("/api/provenance/image/999999")
    assert resp.status_code == 404


@pytest.mark.asyncio
async def test_post_provenance_endpoint(client, db):
    _, post_id = await _seed_full(db)
    resp = await client.get(f"/api/provenance/post/{post_id}")
    assert resp.status_code == 200
    body = await resp.get_json()
    assert body["post"]["id"] == post_id
    assert body["artist"]["slug"] == "alice"


@pytest.mark.asyncio
async def test_post_provenance_404(client):
    resp = await client.get("/api/provenance/post/999999")
    assert resp.status_code == 404
