# app/modules/billing/routes/vendor.py
"""
Billing module vendor routes.

This module wraps the existing vendor billing routes and adds
module-based access control. The actual route implementations remain
in app/api/v1/vendor/billing.py for now, but are accessed through
this module-aware router.

Future: Move all route implementations here for full module isolation.
"""

import logging

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

from app.api.deps import get_current_vendor_api, require_module_access
from app.core.config import settings
from app.core.database import get_db
from app.modules.billing.services import billing_service, subscription_service
from app.modules.enums import FrontendType
from app.modules.tenancy.models import User

logger = logging.getLogger(__name__)

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


# ============================================================================
# Schemas (re-exported from original module)
# ============================================================================


class SubscriptionStatusResponse(BaseModel):
    """Current subscription status and usage."""

    tier_code: str
    tier_name: str
    status: str
    is_trial: bool
    trial_ends_at: str | None = None
    period_start: str | None = None
    period_end: str | None = None
    cancelled_at: str | None = None
    cancellation_reason: str | None = None

    # Usage
    orders_this_period: int
    orders_limit: int | None
    orders_remaining: int | None
    products_count: int
    products_limit: int | None
    products_remaining: int | None
    team_count: int
    team_limit: int | None
    team_remaining: int | None

    # Payment
    has_payment_method: bool
    last_payment_error: str | None = None

    class Config:
        from_attributes = True


class TierResponse(BaseModel):
    """Subscription tier information."""

    code: str
    name: str
    description: str | None = None
    price_monthly_cents: int
    price_annual_cents: int | None = None
    orders_per_month: int | None = None
    products_limit: int | None = None
    team_members: int | None = None
    features: list[str] = []
    is_current: bool = False
    can_upgrade: bool = False
    can_downgrade: bool = False


class TierListResponse(BaseModel):
    """List of available tiers."""

    tiers: list[TierResponse]
    current_tier: str


class InvoiceResponse(BaseModel):
    """Invoice information."""

    id: int
    invoice_number: str | None = None
    invoice_date: str
    due_date: str | None = None
    total_cents: int
    amount_paid_cents: int
    currency: str
    status: str
    pdf_url: str | None = None
    hosted_url: str | None = None


class InvoiceListResponse(BaseModel):
    """List of invoices."""

    invoices: list[InvoiceResponse]
    total: int


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


@vendor_router.get("/subscription", response_model=SubscriptionStatusResponse)
def get_subscription_status(
    current_user: User = Depends(get_current_vendor_api),
    db: Session = Depends(get_db),
):
    """Get current subscription status and usage metrics."""
    vendor_id = current_user.token_vendor_id

    usage = subscription_service.get_usage_summary(db, vendor_id)
    subscription, tier = billing_service.get_subscription_with_tier(db, vendor_id)

    return SubscriptionStatusResponse(
        tier_code=subscription.tier,
        tier_name=tier.name if tier else subscription.tier.title(),
        status=subscription.status.value,
        is_trial=subscription.is_in_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,
        orders_this_period=usage.orders_this_period,
        orders_limit=usage.orders_limit,
        orders_remaining=usage.orders_remaining,
        products_count=usage.products_count,
        products_limit=usage.products_limit,
        products_remaining=usage.products_remaining,
        team_count=usage.team_count,
        team_limit=usage.team_limit,
        team_remaining=usage.team_remaining,
        has_payment_method=bool(subscription.stripe_payment_method_id),
        last_payment_error=subscription.last_payment_error,
    )


@vendor_router.get("/tiers", response_model=TierListResponse)
def get_available_tiers(
    current_user: User = Depends(get_current_vendor_api),
    db: Session = Depends(get_db),
):
    """Get available subscription tiers for upgrade/downgrade."""
    vendor_id = current_user.token_vendor_id
    subscription = subscription_service.get_or_create_subscription(db, vendor_id)
    current_tier = subscription.tier

    tier_list, _ = billing_service.get_available_tiers(db, current_tier)

    tier_responses = [TierResponse(**tier_data) for tier_data in tier_list]

    return TierListResponse(tiers=tier_responses, current_tier=current_tier)


@vendor_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: User = Depends(get_current_vendor_api),
    db: Session = Depends(get_db),
):
    """Get invoice history."""
    vendor_id = current_user.token_vendor_id

    invoices, total = billing_service.get_invoices(db, vendor_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)


# NOTE: Additional endpoints (checkout, portal, cancel, addons, etc.)
# are still handled by app/api/v1/vendor/billing.py for now.
# They can be migrated here as part of a larger refactoring effort.


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

from app.modules.billing.routes.api.vendor_features import vendor_features_router
from app.modules.billing.routes.api.vendor_checkout import vendor_checkout_router
from app.modules.billing.routes.api.vendor_addons import vendor_addons_router
from app.modules.billing.routes.api.vendor_usage import vendor_usage_router

vendor_router.include_router(vendor_features_router, tags=["vendor-features"])
vendor_router.include_router(vendor_checkout_router, tags=["vendor-billing"])
vendor_router.include_router(vendor_addons_router, tags=["vendor-billing-addons"])
vendor_router.include_router(vendor_usage_router, tags=["vendor-usage"])
