# retoor <retoor@molodetz.nl>

import time
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_primary_admin_uid, get_table, invalidate_admins_cache
from devplacepy.utils import clear_user_cache

_counter_cv = [0]


def _signup():
    _counter_cv[0] += 1
    name = f"cav{int(time.time() * 1000)}{_counter_cv[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,
    )
    row = get_table("users").find_one(username=name)
    return name, row["uid"], row["api_key"]


def _make_admin():
    name, uid, key = _signup()
    get_table("users").update({"uid": uid, "role": "Admin"}, ["uid"])
    clear_user_cache(uid)
    return name, uid, key


def _headers(key=None):
    headers = {"Accept": "application/json"}
    if key:
        headers["X-API-KEY"] = key
    return headers


def _create_project(key, title, is_private=False):
    data = {
        "title": title,
        "description": "container access test",
        "project_type": "software",
        "status": "In Development",
    }
    if is_private:
        data["is_private"] = "on"
    r = requests.post(
        f"{BASE_URL}/projects/create", headers=_headers(key), data=data
    )
    assert r.status_code == 200, r.text
    return r.json()["data"]["slug"]


def _containers_data_status(key, slug):
    return requests.get(
        f"{BASE_URL}/projects/{slug}/containers/data", headers=_headers(key)
    ).status_code


def test_admin_private_project_containers_hidden_from_other_admin(app_server):
    _, _, owner_key = _make_admin()
    _, _, other_admin_key = _make_admin()
    slug = _create_project(owner_key, "Admin Container Hidden", is_private=True)
    assert _containers_data_status(other_admin_key, slug) == 404
    assert _containers_data_status(owner_key, slug) == 200


def test_member_private_project_containers_primary_admin_only(app_server):
    _, _, owner_key = _signup()
    _, _, admin_key = _make_admin()
    slug = _create_project(owner_key, "Member Container Hidden", is_private=True)
    assert _containers_data_status(admin_key, slug) == 404
    invalidate_admins_cache()
    primary_key = get_table("users").find_one(uid=get_primary_admin_uid())["api_key"]
    assert _containers_data_status(primary_key, slug) == 200


def test_public_project_containers_visible_to_any_admin(app_server):
    _, _, owner_key = _make_admin()
    _, _, other_admin_key = _make_admin()
    slug = _create_project(owner_key, "Public Container", is_private=False)
    assert _containers_data_status(other_admin_key, slug) == 200
