# retoor <retoor@molodetz.nl>

import time
import pytest
import requests
from tests.conftest import BASE_URL
from devplacepy.database import (
    get_table,
    refresh_snapshot,
    set_setting,
    upsert_seo_metadata,
)
from devplacepy.utils import generate_uid

JSON = {"Accept": "application/json"}
_counter_sm = [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 _post():
    _counter_sm[0] += 1
    name = f"sm{int(time.time() * 1000)}{_counter_sm[0]}"
    s = requests.Session()
    s.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,
    )
    r = s.post(
        f"{BASE_URL}/posts/create",
        headers=JSON,
        data={"title": "seo meta post", "content": "a body for seo meta", "topic": "devlog"},
    )
    return r.json()["data"]["uid"]


def test_invalid_target_type_400(app_server):
    r = requests.get(f"{BASE_URL}/tools/seo-meta/banana/{generate_uid()}")
    assert r.status_code == 400


def test_plain_defaults_when_no_metadata(app_server):
    post_uid = _post()
    r = requests.get(f"{BASE_URL}/tools/seo-meta/post/{post_uid}")
    assert r.status_code == 200
    body = r.json()
    assert body["target_type"] == "post"
    assert body["target_uid"] == post_uid
    assert body["source"] in ("plain", "ai")
    assert "seo_title" in body and "seo_description" in body


def test_ready_metadata_row_is_returned(app_server):
    post_uid = _post()
    upsert_seo_metadata(
        "post",
        post_uid,
        "Crafted SEO Title",
        "A crafted meta description for the post.",
        "alpha, beta, gamma",
        "ready",
        "ai",
    )
    refresh_snapshot()
    r = requests.get(f"{BASE_URL}/tools/seo-meta/post/{post_uid}")
    assert r.status_code == 200
    body = r.json()
    assert body["status"] == "ready"
    assert body["seo_title"] == "Crafted SEO Title"
    assert body["seo_keywords"] == "alpha, beta, gamma"


def test_all_valid_types_resolve(app_server):
    for target_type in ("post", "project", "gist", "news", "issue"):
        r = requests.get(f"{BASE_URL}/tools/seo-meta/{target_type}/{generate_uid()}")
        assert r.status_code in (200, 404), f"{target_type}: {r.status_code}"
