# app/modules/core/routes/api/merchant_dashboard.py
"""
Merchant dashboard statistics endpoint.

Merchant Context: Uses get_merchant_for_current_user to resolve the merchant
from the JWT token. The dependency guarantees an active merchant exists.

This module uses the StatsAggregator service from core to collect metrics from all
enabled modules via the MetricsProvider protocol.
"""

import logging

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

from app.api.deps import get_merchant_for_current_user, require_platform
from app.core.database import get_db
from app.modules.core.schemas.dashboard import MerchantDashboardStatsResponse
from app.modules.core.services.stats_aggregator import stats_aggregator

merchant_dashboard_router = APIRouter(prefix="/dashboard")
logger = logging.getLogger(__name__)


@merchant_dashboard_router.get("/stats", response_model=MerchantDashboardStatsResponse)
def get_merchant_dashboard_stats(
    request: Request,
    merchant=Depends(get_merchant_for_current_user),
    platform=Depends(require_platform),
    db: Session = Depends(get_db),
):
    """
    Get merchant-scoped dashboard statistics.

    Returns aggregated statistics for the current merchant:
    - Active subscriptions
    - Total stores
    - Total customers across all stores
    - Team members across all stores

    Merchant is resolved from the JWT token.
    Requires Authorization header (API endpoint).
    """
    platform_id = platform.id

    flat = stats_aggregator.get_merchant_stats_flat(
        db=db,
        merchant_id=merchant.id,
        platform_id=platform_id,
    )

    return MerchantDashboardStatsResponse(
        active_subscriptions=int(flat.get("billing.active_subscriptions", 0)),
        total_stores=int(flat.get("tenancy.total_stores", 0)),
        total_customers=int(flat.get("customers.total", 0)),
        team_members=int(flat.get("tenancy.team_members", 0)),
    )
