from uuid import UUID

import pytest

from src.workers.tasks.project_deploy import _dispatch_deploy_workflow


@pytest.mark.asyncio
async def test_dispatch_deploy_workflow_uses_workspace_installation(monkeypatch):
    calls: dict[str, object] = {}

    async def resolve(_db_factory, workspace_id):
        calls["workspace_id"] = workspace_id
        return 42

    class FakeGitHub:
        def __init__(self, *, installation_id):
            calls["installation_id"] = installation_id

        async def trigger_workflow_dispatch(self, **kwargs):
            calls["dispatch"] = kwargs
            return True

    monkeypatch.setattr(
        "src.integrations.github_installation.resolve_installation_id_for_workspace",
        resolve,
    )
    monkeypatch.setattr("src.integrations.github_client.GitHubAppClient", FakeGitHub)

    workspace_id = UUID("11111111-1111-1111-1111-111111111111")
    accepted = await _dispatch_deploy_workflow(
        db_factory=object(),
        workspace_id=workspace_id,
        github_repo="P2HS/example",
        branch="preview",
    )

    assert accepted is True
    assert calls["workspace_id"] == workspace_id
    assert calls["installation_id"] == 42
    assert calls["dispatch"] == {
        "repo_full_name": "P2HS/example",
        "workflow_file": "deploy.yml",
        "ref": "preview",
    }


@pytest.mark.asyncio
async def test_dispatch_deploy_workflow_converts_provider_failure_to_retryable_false(monkeypatch):
    async def resolve(*_args):
        raise RuntimeError("GitHub unavailable")

    monkeypatch.setattr(
        "src.integrations.github_installation.resolve_installation_id_for_workspace",
        resolve,
    )

    assert await _dispatch_deploy_workflow(
        db_factory=object(),
        workspace_id=UUID("22222222-2222-2222-2222-222222222222"),
        github_repo="P2HS/example",
        branch="main",
    ) is False
