# app/modules/billing/services/store_platform_sync.py
"""
Keeps store_platforms in sync with merchant subscriptions.

When a subscription is created, reactivated, or deleted, this service
ensures all stores belonging to that merchant get corresponding
StorePlatform entries created or updated.
"""

import logging

from sqlalchemy.orm import Session

from app.modules.tenancy.services.platform_service import platform_service
from app.modules.tenancy.services.store_service import store_service

logger = logging.getLogger(__name__)


class StorePlatformSync:
    """Syncs StorePlatform entries when merchant subscriptions change."""

    def sync_store_platforms_for_merchant(
        self,
        db: Session,
        merchant_id: int,
        platform_id: int,
        is_active: bool,
        tier_id: int | None = None,
    ) -> None:
        """
        Upsert StorePlatform for every store belonging to a merchant.

        - Existing entry → update is_active (and tier_id if provided)
        - Missing + is_active=True → create
        - Missing + is_active=False → no-op
        """
        stores = store_service.get_stores_by_merchant_id(db, merchant_id)

        if not stores:
            return

        for store in stores:
            result = platform_service.ensure_store_platform(
                db, store.id, platform_id, is_active, tier_id
            )
            if result:
                logger.debug(
                    f"Synced StorePlatform store_id={store.id} "
                    f"platform_id={platform_id} is_active={is_active}"
                )

        db.flush()


# Singleton instance
store_platform_sync = StorePlatformSync()
