# app/modules/marketplace/routes/api/store_marketplace.py
"""
Marketplace import endpoints for stores.

Store Context: Uses token_store_id from JWT token (authenticated store API pattern).
The get_current_store_api dependency guarantees token_store_id is present.

All routes require module access control for the 'marketplace' module.
"""

import logging

from fastapi import APIRouter, BackgroundTasks, 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.enums import FrontendType
from app.modules.marketplace.schemas import (
    MarketplaceImportJobRequest,
    MarketplaceImportJobResponse,
)
from app.modules.marketplace.services.marketplace_import_job_service import (
    marketplace_import_job_service,
)
from app.modules.tenancy.schemas.auth import UserContext
from app.modules.tenancy.services.store_service import store_service
from middleware.decorators import rate_limit

store_marketplace_router = APIRouter(
    prefix="/marketplace",
    dependencies=[Depends(require_module_access("marketplace", FrontendType.STORE))],
)
logger = logging.getLogger(__name__)


@store_marketplace_router.post("/import", response_model=MarketplaceImportJobResponse)
@rate_limit(max_requests=10, window_seconds=3600)
async def import_products_from_marketplace(
    request: MarketplaceImportJobRequest,
    background_tasks: BackgroundTasks,
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Import products from marketplace CSV with background processing (Protected).

    The `language` parameter specifies the language code for product
    translations (e.g., 'en', 'fr', 'de'). Default is 'en'.

    For multi-language imports, call this endpoint multiple times with
    different language codes and CSV files containing translations.
    """
    store = store_service.get_store_by_id(db, current_user.token_store_id)

    logger.info(
        f"Starting marketplace import: {request.marketplace} for store {store.store_code} "
        f"by user {current_user.username} (language={request.language})"
    )

    # Create import job (store comes from token)
    import_job = marketplace_import_job_service.create_import_job(
        db, request, store, current_user
    )
    db.commit()

    # Dispatch via task dispatcher (supports Celery or BackgroundTasks)
    from app.tasks.dispatcher import task_dispatcher

    celery_task_id = task_dispatcher.dispatch_marketplace_import(
        background_tasks=background_tasks,
        job_id=import_job.id,
        url=request.source_url,
        marketplace=request.marketplace,
        store_id=store.id,
        batch_size=request.batch_size or 1000,
        language=request.language,
    )

    # Store Celery task ID if using Celery
    if celery_task_id:
        import_job.celery_task_id = celery_task_id
        db.commit()

    return MarketplaceImportJobResponse(
        job_id=import_job.id,
        status="pending",
        marketplace=request.marketplace,
        store_id=import_job.store_id,
        store_code=store.store_code,
        store_name=store.name,
        source_url=request.source_url,
        language=request.language,
        message=f"Marketplace import started from {request.marketplace}. "
        f"Check status with /import-status/{import_job.id}",
        imported=0,
        updated=0,
        total_processed=0,
        error_count=0,
        created_at=import_job.created_at,
    )


@store_marketplace_router.get("/imports/{job_id}", response_model=MarketplaceImportJobResponse)
def get_marketplace_import_status(
    job_id: int,
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Get status of marketplace import job (Protected)."""
    # Service validates that job belongs to store and raises UnauthorizedStoreAccessException if not
    job = marketplace_import_job_service.get_import_job_for_store(
        db, job_id, current_user.token_store_id
    )

    return marketplace_import_job_service.convert_to_response_model(job)


@store_marketplace_router.get("/imports", response_model=list[MarketplaceImportJobResponse])
def get_marketplace_import_jobs(
    marketplace: str | None = Query(None, description="Filter by marketplace"),
    skip: int = Query(0, ge=0),
    limit: int = Query(50, ge=1, le=100),
    current_user: UserContext = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """Get marketplace import jobs for current store (Protected)."""
    store = store_service.get_store_by_id(db, current_user.token_store_id)

    jobs = marketplace_import_job_service.get_import_jobs(
        db=db,
        store=store,
        user=current_user,
        marketplace=marketplace,
        skip=skip,
        limit=limit,
    )

    return [
        marketplace_import_job_service.convert_to_response_model(job) for job in jobs
    ]
