"""Shared fixtures for server tests."""

from __future__ import annotations

import sqlite3
import tempfile

import pytest
from fastapi.testclient import TestClient

from server.app import app
from server.auth import hash_api_key
from server.db import get_db, init_db

TEST_API_KEY = "pt_live_0000000000000000000000000000dead"
TEST_KEY_ID = "pk_testkey0001"
TEST_ORG = "Test Org"
TEST_ADMIN_SECRET = "test-admin-secret"


@pytest.fixture()
def db_conn():
    """Yield a temporary SQLite connection with schema initialized."""
    tmp = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
    tmp.close()
    conn = sqlite3.connect(tmp.name, check_same_thread=False)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA foreign_keys=ON")
    init_db(conn)

    # Seed a test API key
    conn.execute(
        "INSERT INTO api_keys (id, key_hash, org_name) VALUES (?, ?, ?)",
        (TEST_KEY_ID, hash_api_key(TEST_API_KEY), TEST_ORG),
    )
    conn.commit()

    yield conn
    conn.close()


@pytest.fixture()
def client(db_conn, monkeypatch):
    """TestClient with database and admin secret overridden."""
    monkeypatch.setattr("server.config.settings.admin_secret", TEST_ADMIN_SECRET)

    def _override_get_db():
        yield db_conn

    app.dependency_overrides[get_db] = _override_get_db
    with TestClient(app, raise_server_exceptions=False) as c:
        yield c
    app.dependency_overrides.clear()


@pytest.fixture()
def auth_headers():
    """Headers with a valid API key."""
    return {"X-API-Key": TEST_API_KEY}


@pytest.fixture()
def admin_headers():
    """Headers with the admin secret."""
    return {"X-Admin-Secret": TEST_ADMIN_SECRET}
