# retoor <retoor@molodetz.nl>

from datetime import datetime, timezone

import pytest
from fastapi.testclient import TestClient

from devplacepy.database import get_table, purge, refresh_snapshot
from devplacepy.main import app
from devplacepy.services.manager import service_manager
from devplacepy.utils import generate_uid


def _seed_schema():
    now = datetime.now(timezone.utc).isoformat()
    users = get_table("users")
    if "username" not in users.columns:
        users.insert(
            {
                "uid": generate_uid(),
                "username": "dbapi_seed",
                "terms_version": "1",
                "email": "seed@dbapi.test",
                "role": "Member",
                "xp": 0,
                "level": 1,
                "created_at": now,
            }
        )
    bookmarks = get_table("bookmarks")
    if "user_uid" not in bookmarks.columns:
        seed = generate_uid()
        bookmarks.insert(
            {
                "uid": seed,
                "user_uid": "_seedcols",
                "target_type": "post",
                "target_uid": "_s",
                "created_at": now,
                "deleted_at": None,
                "deleted_by": None,
            }
        )
        purge("bookmarks", uid=seed)
    refresh_snapshot()


@pytest.fixture(scope="module")
def client():
    with TestClient(app) as test_client:
        service_manager.set_lock_owner(True)
        _seed_schema()
        yield test_client
        service_manager.set_lock_owner(False)


@pytest.fixture
def auth(client):
    from devplacepy.database import get_primary_admin_uid, invalidate_admins_cache
    from devplacepy.utils import clear_user_cache

    users = get_table("users")
    uid = get_primary_admin_uid()
    if uid is None:
        uid = generate_uid()
        users.insert(
            {
                "uid": uid,
                "username": f"dbapi_admin_{uid[:8]}",
                "terms_version": "1",
                "email": f"{uid[:8]}@dbapi.test",
                "role": "Admin",
                "api_key": f"dbapikey_{uid}",
                "xp": 0,
                "level": 1,
                "created_at": datetime.now(timezone.utc).isoformat(),
            }
        )
        invalidate_admins_cache()
        refresh_snapshot()
    admin = users.find_one(uid=uid)
    key = admin.get("api_key")
    if not key:
        key = f"dbapikey_{uid}"
        users.update({"uid": uid, "api_key": key}, ["uid"])
        clear_user_cache(uid)
        refresh_snapshot()
    return {"X-API-KEY": key}
