from __future__ import annotations

import hashlib
import hmac
import json
import time
from urllib.parse import parse_qs, urlparse

import pytest
from fastapi.testclient import TestClient
from gnexus_gauth.dto import AuthenticatedUser, ClientAccess, TokenSet
from gnexus_gauth.oauth import HttpTokenEndpoint
from gnexus_gauth.runtime import HttpRuntimeUserProvider
from sqlalchemy import select

from app.auth.sessions import create_session, resolve_session
from app.config import Settings, get_settings
from app.main import app
from app.storage.db import Database
from app.storage.models import User, UserSession

AUTH_ENV = {
    "GNEXUS_BOOK_STORAGE_BACKEND": "db",
    "GNEXUS_BOOK_AUTH_CLIENT_ID": "gnexus-book",
    "GNEXUS_BOOK_AUTH_CLIENT_SECRET": "test-client-secret",
    "GNEXUS_BOOK_AUTH_BASE_URL": "https://auth.example.test",
    "GNEXUS_BOOK_AUTH_REDIRECT_URI": "https://book.example.test/auth/callback",
    "GNEXUS_BOOK_AUTH_WEBHOOK_SECRET": "test-webhook-secret",
    "GNEXUS_BOOK_AUTH_COOKIE_SECURE": "false",
}


@pytest.fixture()
def auth_settings(
    database: Database, monkeypatch: pytest.MonkeyPatch
) -> Settings:
    monkeypatch.setenv("GNEXUS_BOOK_DATABASE_URL", database.url)
    for key, value in AUTH_ENV.items():
        monkeypatch.setenv(key, value)
    get_settings.cache_clear()
    settings = get_settings()
    assert settings.auth_enabled
    return settings


def _authorization_state(location: str) -> str:
    query = parse_qs(urlparse(location).query)
    assert query["code_challenge_method"] == ["S256"]
    assert query["client_id"] == ["gnexus-book"]
    return query["state"][0]


def _insert_user(database: Database, sub: str = "sub-2") -> User:
    with database.session() as session:
        with session.begin():
            user = User(sub=sub, email=f"{sub}@example.test", display_name=sub, profile={})
            session.add(user)
            session.flush()
            return user


def _sign(body: str, secret: str, timestamp: int) -> str:
    digest = hmac.new(
        secret.encode(), f"{timestamp}.{body}".encode(), hashlib.sha256
    ).hexdigest()
    return f"t={timestamp},v1={digest}"


def test_me_is_available_with_auth_disabled() -> None:
    client = TestClient(app)

    response = client.get("/me")

    assert response.status_code == 200
    assert response.json() == {
        "auth_enabled": False,
        "user": None,
        "locale": None,
        "locale_effective": "en",
    }


def test_login_requires_configured_client() -> None:
    client = TestClient(app)

    response = client.get("/auth/login", follow_redirects=False)

    assert response.status_code == 400


def test_webhook_requires_configured_client() -> None:
    client = TestClient(app)

    response = client.post("/webhooks/gnexus-auth", content=b"{}")

    assert response.status_code == 503


def test_login_redirect_contains_pkce(auth_settings: Settings) -> None:
    client = TestClient(app)

    response = client.get("/auth/login?return_to=/docs", follow_redirects=False)

    assert response.status_code == 303
    location = response.headers["location"]
    assert location.startswith("https://auth.example.test/oauth/authorize?")
    assert _authorization_state(location)
    assert "scope=" in location


def test_callback_creates_user_session_and_locale(
    auth_settings: Settings,
    database: Database,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    def fake_exchange(self, code: str, verifier: str) -> TokenSet:
        assert code == "test-code"
        assert verifier
        return TokenSet(
            access_token="access",
            refresh_token=None,
            token_type="Bearer",
            expires_in=3600,
        )

    def fake_fetch(self, access_token: str) -> AuthenticatedUser:
        assert access_token == "access"
        return AuthenticatedUser(
            user_id="sub-1",
            email="user@example.test",
            email_verified=True,
            system_role="admin",
            status="active",
            profile={
                "display_name": "Test User",
                "username": "test-user",
                "locale": "ru",
                "avatar_url": None,
            },
            client_access_list=[
                ClientAccess(
                    client_id="gnexus-book",
                    role_ids=["editor"],
                    permission_ids=["docs.write"],
                )
            ],
        )

    monkeypatch.setattr(HttpTokenEndpoint, "exchange_authorization_code", fake_exchange)
    monkeypatch.setattr(HttpRuntimeUserProvider, "fetch_user", fake_fetch)

    client = TestClient(app)
    login = client.get("/auth/login", follow_redirects=False)
    state = _authorization_state(login.headers["location"])

    callback = client.get(
        f"/auth/callback?code=test-code&state={state}", follow_redirects=False
    )
    assert callback.status_code == 303
    assert "gnb_session=" in callback.headers["set-cookie"]

    me = client.get("/me").json()
    assert me["auth_enabled"] is True
    assert me["user"]["user_id"] == "sub-1"
    assert me["user"]["display_name"] == "Test User"
    assert me["user"]["roles"] == ["editor"]
    assert me["locale_effective"] == "ru"

    updated = client.patch("/me", json={"locale": "en"})
    assert updated.status_code == 200
    assert updated.json()["locale"] == "en"
    assert updated.json()["locale_effective"] == "en"

    logout = client.post("/auth/logout")
    assert logout.status_code == 200
    assert client.get("/me").json()["user"] is None

    with database.session() as session:
        user = session.scalars(select(User).where(User.sub == "sub-1")).first()
        assert user is not None
        assert user.email == "user@example.test"
        assert user.locale == "en"


def test_protected_route_requires_session(auth_settings: Settings) -> None:
    client = TestClient(app)

    response = client.get("/docs")

    assert response.status_code == 401


def test_webhook_blocks_user_and_is_idempotent(
    auth_settings: Settings,
    database: Database,
) -> None:
    user = _insert_user(database)
    token, _ = create_session(database, user.id, 3600)

    body = json.dumps(
        {
            "id": "evt_block_1",
            "type": "user.blocked",
            "target": {"user_id": "sub-2"},
            "data": {"user": {"id": "sub-2", "status": "blocked"}},
        }
    )
    timestamp = int(time.time())
    headers = {
        "X-Gnexus-Event-Id": "evt_block_1",
        "X-Gnexus-Event-Type": "user.blocked",
        "X-Gnexus-Event-Timestamp": str(timestamp),
        "X-Gnexus-Signature": _sign(body, "test-webhook-secret", timestamp),
        "Content-Type": "application/json",
    }

    client = TestClient(app)
    response = client.post("/webhooks/gnexus-auth", content=body, headers=headers)
    assert response.status_code == 200
    assert response.json()["duplicate"] is False

    second = client.post("/webhooks/gnexus-auth", content=body, headers=headers)
    assert second.status_code == 200
    assert second.json()["duplicate"] is True

    assert resolve_session(database, token) is None
    with database.session() as session:
        stored = session.scalars(select(User).where(User.sub == "sub-2")).first()
        assert stored is not None and stored.blocked_at is not None
        sessions = session.scalars(
            select(UserSession).where(UserSession.user_id == user.id)
        ).all()
        assert sessions and sessions[0].revoked_at is not None


def test_webhook_rejects_bad_signature(auth_settings: Settings) -> None:
    body = json.dumps({"id": "evt_bad", "type": "user.blocked", "target": {}})
    timestamp = int(time.time())
    headers = {
        "X-Gnexus-Event-Id": "evt_bad",
        "X-Gnexus-Event-Type": "user.blocked",
        "X-Gnexus-Event-Timestamp": str(timestamp),
        "X-Gnexus-Signature": "t=1,v1=deadbeef",
        "Content-Type": "application/json",
    }

    client = TestClient(app)
    response = client.post("/webhooks/gnexus-auth", content=body, headers=headers)

    assert response.status_code == 401


def test_health_stays_public(auth_settings: Settings) -> None:
    client = TestClient(app)

    response = client.get("/health")

    assert response.status_code == 200
    assert response.json()["status"] == "ok"
