# app/modules/billing/routes/api/store.py
"""
Billing module store routes.

Provides subscription status, tier listing, and invoice history
for store-level users. Resolves store_id to (merchant_id, platform_id)
for all billing service calls.
"""

import logging

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.api.deps import get_current_store_api, require_module_access
from app.core.database import get_db
from app.modules.billing.schemas.billing import (
    InvoiceListResponse,
    InvoiceResponse,
    SubscriptionStatusResponse,
    TierListResponse,
    TierResponse,
)
from app.modules.billing.services import billing_service, subscription_service
from app.modules.enums import FrontendType
from app.modules.tenancy.schemas.auth import UserContext

logger = logging.getLogger(__name__)

# Store router with module access control
router = APIRouter(
    prefix="/billing",
    dependencies=[Depends(require_module_access("billing", FrontendType.STORE))],
)


# ============================================================================
# Core Billing Endpoints
# ============================================================================


@router.get("/subscription", response_model=SubscriptionStatusResponse)
def get_subscription_status(
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Get current subscription status."""
    store_id = current_user.token_store_id
    merchant_id, platform_id = subscription_service.resolve_store_to_merchant(db, store_id, current_user.token_platform_id)

    subscription, tier = billing_service.get_subscription_with_tier(db, merchant_id, platform_id)

    feature_codes = sorted(tier.get_feature_codes()) if tier else []

    return SubscriptionStatusResponse(
        tier_code=tier.code if tier else "unknown",
        tier_name=tier.name if tier else "Unknown",
        status=subscription.status,
        is_trial=subscription.status == "trial",
        trial_ends_at=subscription.trial_ends_at.isoformat()
        if subscription.trial_ends_at
        else None,
        period_start=subscription.period_start.isoformat()
        if subscription.period_start
        else None,
        period_end=subscription.period_end.isoformat()
        if subscription.period_end
        else None,
        cancelled_at=subscription.cancelled_at.isoformat()
        if subscription.cancelled_at
        else None,
        cancellation_reason=subscription.cancellation_reason,
        has_payment_method=bool(subscription.stripe_payment_method_id),
        last_payment_error=subscription.last_payment_error,
        feature_codes=feature_codes,
    )


@router.get("/tiers", response_model=TierListResponse)
def get_available_tiers(
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Get available subscription tiers for upgrade/downgrade."""
    store_id = current_user.token_store_id
    merchant_id, platform_id = subscription_service.resolve_store_to_merchant(db, store_id, current_user.token_platform_id)

    subscription = subscription_service.get_or_create_subscription(db, merchant_id, platform_id)
    current_tier_id = subscription.tier_id

    tier_list, _ = billing_service.get_available_tiers(db, current_tier_id, platform_id)

    tier_responses = [TierResponse(**tier_data) for tier_data in tier_list]
    current_tier_code = subscription.tier.code if subscription.tier else "unknown"

    return TierListResponse(tiers=tier_responses, current_tier=current_tier_code)


@router.get("/invoices", response_model=InvoiceListResponse)
def get_invoices(
    skip: int = Query(0, ge=0),
    limit: int = Query(20, ge=1, le=100),
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Get invoice history."""
    store_id = current_user.token_store_id
    merchant_id, platform_id = subscription_service.resolve_store_to_merchant(db, store_id, current_user.token_platform_id)

    invoices, total = billing_service.get_invoices(db, merchant_id, skip=skip, limit=limit)

    invoice_responses = [
        InvoiceResponse(
            id=inv.id,
            invoice_number=inv.invoice_number,
            invoice_date=inv.invoice_date.isoformat(),
            due_date=inv.due_date.isoformat() if inv.due_date else None,
            total_cents=inv.total_cents,
            amount_paid_cents=inv.amount_paid_cents,
            currency=inv.currency,
            status=inv.status,
            pdf_url=inv.invoice_pdf_url,
            hosted_url=inv.hosted_invoice_url,
        )
        for inv in invoices
    ]

    return InvoiceListResponse(invoices=invoice_responses, total=total)


# ============================================================================
# Aggregate Sub-Routers
# ============================================================================
# Include all billing-related store sub-routers

from app.modules.billing.routes.api.store_addons import store_addons_router
from app.modules.billing.routes.api.store_checkout import store_checkout_router
from app.modules.billing.routes.api.store_features import store_features_router
from app.modules.billing.routes.api.store_usage import store_usage_router

router.include_router(store_features_router, tags=["store-features"])
router.include_router(store_checkout_router, tags=["store-billing"])
router.include_router(store_addons_router, tags=["store-billing-addons"])
router.include_router(store_usage_router, tags=["store-usage"])
