from __future__ import annotations

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

import pygit2
import pytest
from fastapi import FastAPI
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.permissions import Permission, PermissionsMap, permission_key
from pygitweb.tasks import board_router

_BOARDS_AUTH = AuthConfig(
	auth_mode="local",
	local_users=[LocalUser(user="admin", password="secret"), LocalUser(user="viewer", password="secret")],
	oauth_permissions=PermissionsMap.model_validate({
		"*": [],
		permission_key(Permission.BOARDS, "demo"): ["admin"],
	}),
)


def _build_client() -> TestClient:
	app = FastAPI()
	app.include_router(board_router, prefix="/board")
	return TestClient(app)


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 board_env(tmp_path: Path) -> Generator[dict[str, str | TestClient], None, None]:
	repo_dir = tmp_path / "demo"
	repo = pygit2.init_repository(str(repo_dir), bare=False)
	_create_initial_commit(repo, repo_dir)
	with (
		patch.object(settings, "PROJECTROOT", str(tmp_path)),
		patch.object(settings, "PROJECTS_LIST", str(tmp_path)),
		patch.object(settings, "STRICT_EXPORT", False),
		patch.object(settings, "EXPORT_OK", ""),
		patch.object(settings, "LIST_ALL", True),
		patch("pygitweb.auth_config.auth_config", _BOARDS_AUTH),
		patch("pygitweb.auth.auth_config", _BOARDS_AUTH),
	):
		yield {"client": _build_client(), "project": "demo"}


def test_board_post_open_when_auth_disabled(board_env: dict[str, str | TestClient]) -> None:
	client = board_env["client"]
	assert isinstance(client, TestClient)
	with patch.object(settings, "AUTH", False):
		r = client.post(
			"/board/create",
			params={"project": board_env["project"], "name": "temp"},
		)
	assert r.status_code == 200


def test_board_create_401_without_login(board_env: dict[str, str | TestClient]) -> None:
	client = board_env["client"]
	assert isinstance(client, TestClient)
	with patch.object(settings, "AUTH", True):
		r = client.post(
			"/board/create",
			params={"project": board_env["project"], "name": "temp"},
		)
	assert r.status_code == 401


def test_board_create_allowed_with_grant(board_env: dict[str, str | TestClient]) -> None:
	client = board_env["client"]
	assert isinstance(client, TestClient)
	with patch.object(settings, "AUTH", True), client_as_user(client, "admin"):
		r = client.post(
			"/board/create",
			params={"project": board_env["project"], "name": "temp-board"},
		)
	assert r.status_code == 200


def test_board_create_forbidden_without_grant(board_env: dict[str, str | TestClient]) -> None:
	client = board_env["client"]
	assert isinstance(client, TestClient)
	with patch.object(settings, "AUTH", True), client_as_user(client, "viewer"):
		r = client.post(
			"/board/create",
			params={"project": board_env["project"], "name": "temp-board"},
		)
	assert r.status_code == 403


def test_board_delete_forbidden_without_grant(board_env: dict[str, str | TestClient]) -> None:
	client = board_env["client"]
	assert isinstance(client, TestClient)
	with patch.object(settings, "AUTH", True), client_as_user(client, "viewer"):
		r = client.post(
			"/board/delete",
			params={"project": board_env["project"], "name": "Tasks"},
		)
	assert r.status_code == 403