# app/api/v1/admin/marketplace.py
"""
Marketplace import job monitoring endpoints for admin.
"""

import logging

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

from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.services.marketplace_import_job_service import marketplace_import_job_service
from app.services.stats_service import stats_service
from app.services.vendor_service import vendor_service
from app.tasks.background_tasks import process_marketplace_import
from models.database.user import User
from models.schema.marketplace_import_job import (
    AdminMarketplaceImportJobListResponse,
    AdminMarketplaceImportJobRequest,
    AdminMarketplaceImportJobResponse,
    MarketplaceImportJobRequest,
    MarketplaceImportJobResponse,
)

router = APIRouter(prefix="/marketplace-import-jobs")
logger = logging.getLogger(__name__)


@router.get("", response_model=AdminMarketplaceImportJobListResponse)
def get_all_marketplace_import_jobs(
    marketplace: str | None = Query(None),
    status: str | None = Query(None),
    page: int = Query(1, ge=1),
    limit: int = Query(100, ge=1, le=100),
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_api),
):
    """Get all marketplace import jobs with pagination (Admin only)."""
    jobs, total = marketplace_import_job_service.get_all_import_jobs_paginated(
        db=db,
        marketplace=marketplace,
        status=status,
        page=page,
        limit=limit,
    )

    return AdminMarketplaceImportJobListResponse(
        items=[
            marketplace_import_job_service.convert_to_admin_response_model(job)
            for job in jobs
        ],
        total=total,
        page=page,
        limit=limit,
    )


@router.post("", response_model=MarketplaceImportJobResponse)
async def create_marketplace_import_job(
    request: AdminMarketplaceImportJobRequest,
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_api),
):
    """
    Create a new marketplace import job (Admin only).

    Admins can trigger imports for any vendor by specifying vendor_id.
    The import is processed asynchronously in the background.
    """
    vendor = vendor_service.get_vendor_by_id(db, request.vendor_id)

    job_request = MarketplaceImportJobRequest(
        source_url=request.source_url,
        marketplace=request.marketplace,
        batch_size=request.batch_size,
    )

    job = marketplace_import_job_service.create_import_job(
        db=db,
        request=job_request,
        vendor=vendor,
        user=current_admin,
    )
    db.commit()

    logger.info(
        f"Admin {current_admin.username} created import job {job.id} "
        f"for vendor {vendor.vendor_code}"
    )

    background_tasks.add_task(
        process_marketplace_import,
        job.id,
        request.source_url,
        request.marketplace,
        vendor.id,
        request.batch_size or 1000,
    )

    return marketplace_import_job_service.convert_to_response_model(job)


# NOTE: /stats must be defined BEFORE /{job_id} to avoid route conflicts
@router.get("/stats")
def get_import_statistics(
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_api),
):
    """Get marketplace import statistics (Admin only)."""
    return stats_service.get_import_statistics(db)


@router.get("/{job_id}", response_model=AdminMarketplaceImportJobResponse)
def get_marketplace_import_job(
    job_id: int,
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin_api),
):
    """Get a single marketplace import job by ID (Admin only)."""
    job = marketplace_import_job_service.get_import_job_by_id_admin(db, job_id)
    return marketplace_import_job_service.convert_to_admin_response_model(job)
