"""Shared fixtures for serve/ router tests.

The fixture patches data_dir on whichever module owns it — works against
both the pre-split monolith (bincio.serve.server) and the post-split
layout (bincio.serve.deps).
"""
from __future__ import annotations

from pathlib import Path

import pytest
from fastapi.testclient import TestClient

from bincio.serve.db import create_session, create_user, open_db


def _set_data_dir(path: Path) -> None:
    try:
        import bincio.serve.deps as deps
        deps.data_dir = path
        deps._db = None
    except (ImportError, AttributeError):
        import bincio.serve.server as srv
        srv.data_dir = path
        srv._db = None


def _get_data_dir() -> Path | None:
    try:
        import bincio.serve.deps as deps
        return deps.data_dir
    except (ImportError, AttributeError):
        import bincio.serve.server as srv
        return srv.data_dir


@pytest.fixture()
def tmp_data(tmp_path: Path) -> Path:
    """Return a tmp_path with a valid instance.db."""
    open_db(tmp_path)   # creates schema
    return tmp_path


@pytest.fixture()
def client(tmp_data: Path) -> TestClient:
    from bincio.serve.server import app
    _set_data_dir(tmp_data)
    return TestClient(app, raise_server_exceptions=False)


@pytest.fixture()
def admin_client(tmp_data: Path) -> TestClient:
    """Client with an admin session cookie pre-set."""
    from bincio.serve.server import app
    _set_data_dir(tmp_data)

    db = open_db(tmp_data)
    create_user(db, "admin", "Admin", "adminpass1", is_admin=True,
                wiki_access=True, activity_access=True)
    token = create_session(db, "admin")

    c = TestClient(app, raise_server_exceptions=False)
    c.cookies.set("bincio_session", token)
    return c


@pytest.fixture()
def user_client(tmp_data: Path) -> TestClient:
    """Client with a regular (non-admin) session cookie pre-set."""
    from bincio.serve.server import app
    _set_data_dir(tmp_data)

    db = open_db(tmp_data)
    create_user(db, "alice", "Alice", "alicepass1", is_admin=False,
                wiki_access=True, activity_access=True)
    (tmp_data / "alice" / "activities").mkdir(parents=True, exist_ok=True)
    token = create_session(db, "alice")

    c = TestClient(app, raise_server_exceptions=False)
    c.cookies.set("bincio_session", token)
    return c
