from __future__ import annotations

from collections.abc import Generator
from pathlib import Path
from unittest.mock import patch

import pygit2
import pytest
from fastapi.testclient import TestClient

from pygitweb.auth_config import AuthConfig, LocalUser
from pygitweb.config import settings
from pygitweb.conftest import client_as_user
from pygitweb.main import app
from pygitweb.permissions import Permission, permission_key, permissions_with_defaults

_HOOKS_AUTH = AuthConfig(
	auth_mode="local",
	local_users=[LocalUser(user="admin", password="secret"), LocalUser(user="viewer", password="secret")],
	oauth_permissions=permissions_with_defaults({
		permission_key(Permission.HOOKS, "demo"): ["admin"],
	}),
)


def _create_initial_commit(repo: pygit2.Repository, repo_dir: Path) -> None:
	(repo_dir / "README.md").write_text("seed\n", encoding="utf-8")
	index = repo.index
	index.add("README.md")
	index.write()
	tree = index.write_tree()
	sig = pygit2.Signature("tester", "tester@example.com")
	repo.create_commit("HEAD", sig, sig, "initial", tree, [])


@pytest.fixture
def hook_env(tmp_path: Path) -> Generator[dict[str, str], None, None]:
	root = tmp_path / "root"
	root.mkdir()
	repo_dir = root / "demo"
	repo_dir.mkdir()
	_create_initial_commit(pygit2.init_repository(str(repo_dir), bare=False), repo_dir)
	with (
		patch.object(settings, "PROJECTROOT", str(root)),
		patch.object(settings, "PROJECTS_LIST", str(root)),
		patch.object(settings, "PROJECT_MAXDEPTH", 3),
		patch.object(settings, "STRICT_EXPORT", False),
		patch.object(settings, "EXPORT_OK", ""),
		patch.object(settings, "LIST_ALL", True),
		patch.object(settings, "MAXLOAD", None),
		patch("pygitweb.auth_config.auth_config", _HOOKS_AUTH),
		patch("pygitweb.auth.auth_config", _HOOKS_AUTH),
		patch("pygitweb.main.auth_config", _HOOKS_AUTH),
	):
		yield {"project": "demo"}


@pytest.fixture
def client() -> Generator[TestClient, None, None]:
	with TestClient(app) as c:
		yield c


def test_hook_check_open_when_auth_disabled(client: TestClient, hook_env: dict[str, str]) -> None:
	with patch.object(settings, "AUTH", False):
		r = client.post(
			f"/project/{hook_env['project']}/hook",
			params={"name": "post-receive.notify", "op": "check"},
		)
	assert r.status_code == 200


def test_hook_add_open_when_auth_disabled(client: TestClient, hook_env: dict[str, str]) -> None:
	with patch.object(settings, "AUTH", False):
		r = client.post(
			f"/project/{hook_env['project']}/hook",
			params={"name": "post-receive.notify", "op": "add"},
		)
	assert r.status_code == 200


def test_hook_add_401_without_login(client: TestClient, hook_env: dict[str, str]) -> None:
	with patch.object(settings, "AUTH", True):
		r = client.post(
			f"/project/{hook_env['project']}/hook",
			params={"name": "post-receive.notify", "op": "add"},
		)
	assert r.status_code == 404


def test_hook_add_allowed_with_grant(client: TestClient, hook_env: dict[str, str]) -> None:
	with patch.object(settings, "AUTH", True), client_as_user(client, "admin"):
		r = client.post(
			f"/project/{hook_env['project']}/hook",
			params={"name": "post-receive.notify", "op": "add"},
		)
	assert r.status_code == 200


def test_hook_add_forbidden_without_grant(client: TestClient, hook_env: dict[str, str]) -> None:
	with patch.object(settings, "AUTH", True), client_as_user(client, "viewer"):
		r = client.post(
			f"/project/{hook_env['project']}/hook",
			params={"name": "post-receive.notify", "op": "add"},
		)
	assert r.status_code == 403


def test_hook_check_allowed_without_hooks_grant(client: TestClient, hook_env: dict[str, str]) -> None:
	with patch.object(settings, "AUTH", True), client_as_user(client, "viewer"):
		r = client.post(
			f"/project/{hook_env['project']}/hook",
			params={"name": "post-receive.notify", "op": "check"},
		)
	assert r.status_code == 200