# retoor <retoor@molodetz.nl>

import time
import pytest
import requests
from tests.conftest import BASE_URL
from devplacepy.database import (
    create_deepsearch_session,
    get_table,
    refresh_snapshot,
    set_setting,
)
from devplacepy.services.jobs import queue

JSON = {"Accept": "application/json"}
_counter_ds = [0]


@pytest.fixture(scope="module", autouse=True)
def _settings(app_server):
    set_setting("rate_limit_per_minute", "1000000")
    set_setting("registration_open", "1")
    yield


def _user():
    _counter_ds[0] += 1
    name = f"dsc{int(time.time() * 1000)}{_counter_ds[0]}"
    requests.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@t.dev",
            "password": "secret123",
            "confirm_password": "secret123",
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    refresh_snapshot()
    user = get_table("users").find_one(username=name)
    return user["uid"], user["api_key"]


def _seed_session(owner_id, with_session=True):
    uid = queue.enqueue(
        "deepsearch",
        {"query": "q", "depth": 1, "max_pages": 5},
        "user",
        owner_id,
        "DeepSearch",
    )
    if with_session:
        create_deepsearch_session(
            uid, "user", owner_id, "q", 1, 5, f"ds_{uid.replace('-', '')}"
        )
    refresh_snapshot()
    return uid


def test_pause_resume_cancel_owner(app_server):
    uid_owner, key = _user()
    uid = _seed_session(uid_owner)
    h = {"X-API-KEY": key, **JSON}
    for action, state in (("pause", "paused"), ("resume", "running"), ("cancel", "cancelled")):
        r = requests.post(f"{BASE_URL}/tools/deepsearch/{uid}/{action}", headers=h)
        assert r.status_code == 200, f"{action}: {r.text[:200]}"
        assert r.json()["ok"] is True
        assert r.json()["state"] == state


def test_control_non_owner_forbidden(app_server):
    owner_uid, _ = _user()
    _, other_key = _user()
    uid = _seed_session(owner_uid)
    r = requests.post(
        f"{BASE_URL}/tools/deepsearch/{uid}/pause",
        headers={"X-API-KEY": other_key, **JSON},
    )
    assert r.status_code == 403


def test_control_unknown_uid_404(app_server):
    _, key = _user()
    r = requests.post(
        f"{BASE_URL}/tools/deepsearch/no-such-uid/pause",
        headers={"X-API-KEY": key, **JSON},
    )
    assert r.status_code == 404


def test_control_job_without_session_404(app_server):
    owner_uid, key = _user()
    uid = _seed_session(owner_uid, with_session=False)
    r = requests.post(
        f"{BASE_URL}/tools/deepsearch/{uid}/pause",
        headers={"X-API-KEY": key, **JSON},
    )
    assert r.status_code == 404
