"""Free plan checkout: no Stripe price; workspace update only."""
from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4

import pytest

from src.domain.billing.constants import FREE_PLAN_SLUG
from src.domain.billing.service import BillingService


@pytest.mark.asyncio
async def test_start_subscription_checkout_free_skips_stripe():
    catalog = AsyncMock()
    catalog.get_plan_by_slug = AsyncMock(
        return_value=SimpleNamespace(slug=FREE_PLAN_SLUG)
    )

    workspace_repo = AsyncMock()
    workspace_repo.update = AsyncMock()
    workspace_repo.clear_billing_checkout_tracking = AsyncMock()

    svc = BillingService(
        customer_repo=AsyncMock(),
        subscription_repo=AsyncMock(),
        invoice_repo=AsyncMock(),
        event_repo=AsyncMock(),
        usage_repo=AsyncMock(),
        purchase_repo=AsyncMock(),
        ledger_repo=AsyncMock(),
        catalog=catalog,
        stripe_client=None,
        workspace_repo=workspace_repo,
    )

    ws_id = uuid4()
    svc._subscription_repo.get_latest_for_workspace.return_value = None
    user_id = uuid4()
    out = await svc.start_subscription_checkout(
        workspace_id=ws_id,
        user_id=user_id,
        email="a@b.com",
        workspace_name="W",
        plan_slug="free",
        interval="month",
        success_url="https://x/s",
        cancel_url="https://x/c",
    )

    assert out["free_plan"] is True
    assert out["checkout_url"] is None
    assert out["session_id"] is None
    assert out["workspace_id"] == ws_id
    workspace_repo.update.assert_awaited_once_with(
        ws_id,
        selected_plan_slug=FREE_PLAN_SLUG,
        onboarding_status="plan_selected",
    )
    workspace_repo.clear_billing_checkout_tracking.assert_awaited_once_with(ws_id)
