"""Race-safe get_or_create helper (shared by the async services)."""

import pytest
from sqlalchemy import select

from backend.app.models import Artist
from backend.app.services.db_helpers import get_or_create

pytestmark = pytest.mark.integration


@pytest.mark.asyncio
async def test_get_or_create_creates_then_returns_existing(db):
    stmt = select(Artist).where(Artist.slug == "goc-test")

    factory_calls = {"n": 0}

    async def _make():
        factory_calls["n"] += 1
        a = Artist(name="GOC Test", slug="goc-test")
        db.add(a)
        await db.flush()
        return a

    row1, created1 = await get_or_create(db, stmt, _make)
    assert created1 is True
    assert row1.slug == "goc-test"
    assert factory_calls["n"] == 1

    # Second call finds the existing row and does NOT invoke the factory.
    row2, created2 = await get_or_create(db, stmt, _make)
    assert created2 is False
    assert row2.id == row1.id
    assert factory_calls["n"] == 1  # factory not called when the row exists
