import pytest
from sqlalchemy import select

from backend.app.models import AppSetting

pytestmark = pytest.mark.integration


@pytest.mark.asyncio
async def test_app_setting_table_round_trip(db):
    db.add(AppSetting(key="extension_api_key", value="abc123"))
    await db.flush()
    row = (await db.execute(
        select(AppSetting).where(AppSetting.key == "extension_api_key")
    )).scalar_one()
    assert row.value == "abc123"
    assert row.updated_at is not None


@pytest.mark.asyncio
async def test_app_setting_upsert(db):
    db.add(AppSetting(key="k", value="v1"))
    await db.flush()
    row = (await db.execute(
        select(AppSetting).where(AppSetting.key == "k")
    )).scalar_one()
    row.value = "v2"
    await db.flush()
    again = (await db.execute(
        select(AppSetting.value).where(AppSetting.key == "k")
    )).scalar_one()
    assert again == "v2"
