# app/modules/billing/tests/integration/test_platform_routes.py
"""
Integration tests for platform pricing API routes (public, no auth).

Tests the public pricing endpoints at:
    /api/v1/platform/pricing/*

These are unauthenticated endpoints used by the marketing site and signup flow.
"""

import uuid

import pytest

from app.modules.billing.models import (
    AddOnProduct,
    SubscriptionTier,
    TierCode,
)
from app.modules.tenancy.models import Platform

# ============================================================================
# Fixtures
# ============================================================================

BASE = "/api/v1/platform/pricing"


@pytest.fixture
def pricing_platform(db):
    """Create a platform for pricing tests."""
    platform = Platform(
        code=f"pricing_{uuid.uuid4().hex[:8]}",
        name="Pricing Test Platform",
        is_active=True,
    )
    db.add(platform)
    db.commit()
    db.refresh(platform)
    return platform


@pytest.fixture
def pricing_tiers(db, pricing_platform):
    """Create public subscription tiers for pricing display."""
    tiers = []
    for i, (code, name, price_m, price_a) in enumerate([
        (TierCode.ESSENTIAL.value, "Essential", 0, 0),
        (TierCode.PROFESSIONAL.value, "Professional", 2900, 29000),
        (TierCode.BUSINESS.value, "Business", 7900, 79000),
        (TierCode.ENTERPRISE.value, "Enterprise", 19900, 199000),
    ]):
        tier = SubscriptionTier(
            code=code,
            name=name,
            description=f"{name} plan for growing businesses",
            price_monthly_cents=price_m,
            price_annual_cents=price_a,
            display_order=i,
            is_active=True,
            is_public=True,
            platform_id=pricing_platform.id,
        )
        db.add(tier)
        tiers.append(tier)
    db.commit()
    for t in tiers:
        db.refresh(t)
    return tiers


@pytest.fixture
def pricing_addons(db):
    """Create add-on products for pricing display."""
    addons = []
    for code, name, cat, price in [
        ("custom_domain", "Custom Domain", "hosting", 499),
        ("extra_products", "Extra Products Pack", "capacity", 999),
    ]:
        addon = AddOnProduct(
            code=code,
            name=name,
            description=f"{name} add-on",
            category=cat,
            price_cents=price,
            billing_period="monthly",
            is_active=True,
        )
        db.add(addon)
        addons.append(addon)
    db.commit()
    for a in addons:
        db.refresh(a)
    return addons


# ============================================================================
# GET /pricing/tiers
# ============================================================================


class TestPlatformGetTiers:
    """Tests for GET /api/v1/platform/pricing/tiers."""

    def test_get_tiers_success(self, client, pricing_tiers):
        response = client.get(f"{BASE}/tiers")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        assert len(data) >= 4

    def test_get_tiers_response_shape(self, client, pricing_tiers):
        response = client.get(f"{BASE}/tiers")
        assert response.status_code == 200
        tier = response.json()[0]
        assert "code" in tier
        assert "name" in tier
        assert "price_monthly" in tier
        assert "price_monthly_cents" in tier
        assert "feature_codes" in tier

    def test_get_tiers_excludes_inactive(self, client, pricing_tiers, db):
        pricing_tiers[3].is_active = False
        db.commit()

        response = client.get(f"{BASE}/tiers")
        assert response.status_code == 200
        codes = [t["code"] for t in response.json()]
        assert TierCode.ENTERPRISE.value not in codes

    def test_get_tiers_popular_flag(self, client, pricing_tiers):
        response = client.get(f"{BASE}/tiers")
        assert response.status_code == 200
        for tier in response.json():
            if tier["code"] == TierCode.PROFESSIONAL.value:
                assert tier["is_popular"] is True
            elif tier["code"] == TierCode.ENTERPRISE.value:
                assert tier["is_enterprise"] is True

    def test_get_tiers_empty(self, client):
        response = client.get(f"{BASE}/tiers")
        assert response.status_code == 200
        assert response.json() == []


# ============================================================================
# GET /pricing/tiers/{tier_code}
# ============================================================================


class TestPlatformGetTier:
    """Tests for GET /api/v1/platform/pricing/tiers/{tier_code}."""

    def test_get_tier_success(self, client, pricing_tiers):
        response = client.get(f"{BASE}/tiers/{TierCode.PROFESSIONAL.value}")
        assert response.status_code == 200
        data = response.json()
        assert data["code"] == TierCode.PROFESSIONAL.value
        assert data["price_monthly_cents"] == 2900
        assert data["price_annual_cents"] == 29000
        assert data["price_monthly"] == 29.0

    def test_get_tier_not_found(self, client):
        response = client.get(f"{BASE}/tiers/nonexistent")
        assert response.status_code == 404


# ============================================================================
# GET /pricing/addons
# ============================================================================


class TestPlatformGetAddons:
    """Tests for GET /api/v1/platform/pricing/addons."""

    def test_get_addons_success(self, client, pricing_addons):
        response = client.get(f"{BASE}/addons")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        assert len(data) >= 2

    def test_get_addons_response_shape(self, client, pricing_addons):
        response = client.get(f"{BASE}/addons")
        assert response.status_code == 200
        addon = response.json()[0]
        assert "code" in addon
        assert "name" in addon
        assert "price" in addon
        assert "price_cents" in addon
        assert "category" in addon

    def test_get_addons_empty(self, client):
        response = client.get(f"{BASE}/addons")
        assert response.status_code == 200
        assert response.json() == []


# ============================================================================
# GET /pricing (full pricing page)
# ============================================================================


class TestPlatformGetPricing:
    """Tests for GET /api/v1/platform/pricing."""

    def test_get_pricing_success(self, client, pricing_tiers, pricing_addons):
        response = client.get(f"{BASE}")
        assert response.status_code == 200
        data = response.json()
        assert "tiers" in data
        assert "addons" in data
        assert "trial_days" in data
        assert "annual_discount_months" in data
        assert len(data["tiers"]) >= 4
        assert len(data["addons"]) >= 2
        assert data["annual_discount_months"] == 2

    def test_get_pricing_empty_db(self, client):
        response = client.get(f"{BASE}")
        assert response.status_code == 200
        data = response.json()
        assert data["tiers"] == []
        assert data["addons"] == []
        assert "trial_days" in data
