from typing import Annotated, Any, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from apps.api.dependencies import get_current_user, get_current_tenant, require_permission
from infrastructure.database.session import get_db
from modules.identity.models import User
from modules.tenants.models import Tenant, TenantMember
from modules.bots.schemas import (
    BotRegisterRequest,
    BotUpdateRequest,
    BotResponse,
    BotDetailResponse,
    BotUserResponse,
    ToggleModuleRequest,
    ToggleModuleTriggerRequest,
    UpdateModuleConfigRequest,
    InstallModuleRequest,
    VerifyAdminRequest,
    VerifyModuleRequest,
    BotModuleResponse,
    CreateRedeemCodeRequest,
    UpdateRedeemCodeRequest,
    RedeemCodeResponse,
    RedeemLogResponse,
    CreateBotFileRequest,
    BotFileResponse,
    ReplySupportTicketRequest,
    BotSupportTicketResponse,
)
from modules.bots.service import BotService
from modules.bots.modular_engine import BotModuleService
from shared.schemas import ApiResponse

router = APIRouter(prefix="/bots", tags=["Telegram Bots Management"])


@router.get("", response_model=ApiResponse[list[BotResponse]], status_code=status.HTTP_200_OK)
async def list_tenant_bots(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = BotService(db)
    bots = await service.list_bots(tenant_id=tenant.id)
    return ApiResponse(
        message="Tenant bots retrieved successfully",
        data=bots,
    )


@router.post("", response_model=ApiResponse[BotDetailResponse], status_code=status.HTTP_201_CREATED)
async def register_bot(
    req: BotRegisterRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = BotService(db)
    bot = await service.register_bot(tenant_id=tenant.id, req=req)

    user_count = await service.repo.count_bot_users(bot.id)
    return ApiResponse(
        message=f"Bot @{bot.username} registered successfully",
        data=BotDetailResponse(
            id=bot.id,
            tenant_id=bot.tenant_id,
            name=bot.name,
            username=bot.username,
            status=bot.status,
            default_locale=bot.default_locale,
            webhook_url=bot.webhook.webhook_url if bot.webhook else None,
            webhook_active=bot.webhook.is_active if bot.webhook else False,
            settings=bot.settings.settings_json if bot.settings else {},
            total_users=user_count,
            created_at=bot.created_at,
            updated_at=bot.updated_at,
        ),
    )


@router.get("/{bot_id}", response_model=ApiResponse[BotDetailResponse], status_code=status.HTTP_200_OK)
async def get_bot_details(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = BotService(db)
    bot = await service.get_bot(bot_id, tenant_id=tenant.id)
    user_count = await service.repo.count_bot_users(bot.id)

    return ApiResponse(
        message="Bot details retrieved successfully",
        data=BotDetailResponse(
            id=bot.id,
            tenant_id=bot.tenant_id,
            name=bot.name,
            username=bot.username,
            status=bot.status,
            default_locale=bot.default_locale,
            webhook_url=bot.webhook.webhook_url if bot.webhook else None,
            webhook_active=bot.webhook.is_active if bot.webhook else False,
            settings=bot.settings.settings_json if bot.settings else {},
            total_users=user_count,
            created_at=bot.created_at,
            updated_at=bot.updated_at,
        ),
    )


@router.patch("/{bot_id}", response_model=ApiResponse[BotDetailResponse], status_code=status.HTTP_200_OK)
async def update_bot(
    bot_id: UUID,
    req: BotUpdateRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = BotService(db)
    bot = await service.update_bot(bot_id=bot_id, tenant_id=tenant.id, req=req)
    user_count = await service.repo.count_bot_users(bot.id)

    return ApiResponse(
        message="Bot updated successfully",
        data=BotDetailResponse(
            id=bot.id,
            tenant_id=bot.tenant_id,
            name=bot.name,
            username=bot.username,
            status=bot.status,
            default_locale=bot.default_locale,
            webhook_url=bot.webhook.webhook_url if bot.webhook else None,
            webhook_active=bot.webhook.is_active if bot.webhook else False,
            settings=bot.settings.settings_json if bot.settings else {},
            total_users=user_count,
            created_at=bot.created_at,
            updated_at=bot.updated_at,
        ),
    )


@router.delete("/{bot_id}", response_model=ApiResponse[None], status_code=status.HTTP_200_OK)
async def delete_bot(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = BotService(db)
    await service.delete_bot(bot_id=bot_id, tenant_id=tenant.id)
    return ApiResponse(
        message="Bot deleted successfully",
        data=None,
    )


@router.post("/{bot_id}/activate", response_model=ApiResponse[BotResponse], status_code=status.HTTP_200_OK)
async def activate_bot(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = BotService(db)
    bot = await service.activate_bot(bot_id=bot_id, tenant_id=tenant.id)
    user_count = await service.repo.count_bot_users(bot.id)

    return ApiResponse(
        message="Bot activated successfully",
        data=BotResponse(
            id=bot.id,
            tenant_id=bot.tenant_id,
            name=bot.name,
            username=bot.username,
            status=bot.status,
            default_locale=bot.default_locale,
            webhook_url=bot.webhook.webhook_url if bot.webhook else None,
            webhook_active=bot.webhook.is_active if bot.webhook else False,
            total_users=user_count,
            created_at=bot.created_at,
            updated_at=bot.updated_at,
        ),
    )


@router.post("/{bot_id}/deactivate", response_model=ApiResponse[BotResponse], status_code=status.HTTP_200_OK)
async def deactivate_bot(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = BotService(db)
    bot = await service.deactivate_bot(bot_id=bot_id, tenant_id=tenant.id)
    user_count = await service.repo.count_bot_users(bot.id)

    return ApiResponse(
        message="Bot deactivated successfully",
        data=BotResponse(
            id=bot.id,
            tenant_id=bot.tenant_id,
            name=bot.name,
            username=bot.username,
            status=bot.status,
            default_locale=bot.default_locale,
            webhook_url=bot.webhook.webhook_url if bot.webhook else None,
            webhook_active=bot.webhook.is_active if bot.webhook else False,
            total_users=user_count,
            created_at=bot.created_at,
            updated_at=bot.updated_at,
        ),
    )


@router.get("/{bot_id}/users", response_model=ApiResponse[list[BotUserResponse]], status_code=status.HTTP_200_OK)
async def list_bot_users(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
    limit: int = Query(default=100, ge=1, le=500),
    offset: int = Query(default=0, ge=0),
):
    tenant, _ = tenant_context
    service = BotService(db)
    # Ensure bot belongs to tenant
    await service.get_bot(bot_id, tenant_id=tenant.id)

    users = await service.repo.get_bot_users(bot_id, limit=limit, offset=offset)
    return ApiResponse(
        message="Bot users retrieved successfully",
        data=[BotUserResponse.model_validate(u) for u in users],
    )


# ==============================================================================
# BOT MODULAR FEATURE SYSTEM (INSTALL, CONFIGURE, TOGGLE, EXECUTE)
# ==============================================================================

@router.get("/{bot_id}/modules", response_model=ApiResponse[list[BotModuleResponse]], status_code=status.HTTP_200_OK)
async def list_bot_modules(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Lists all available modules and their activation/configuration state for this bot."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    modules = await mod_service.list_bot_modules(bot_id)
    return ApiResponse(
        message="Bot modules retrieved successfully",
        data=[BotModuleResponse(**m) for m in modules],
    )


@router.post("/{bot_id}/modules/{module_id}/install", response_model=ApiResponse[dict[str, Any]], status_code=status.HTTP_201_CREATED)
async def install_bot_module(
    bot_id: UUID,
    module_id: str,
    req: InstallModuleRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Installs and activates a feature module on the specified Telegram Bot."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    mod = await mod_service.install_module(bot_id, module_id, config=req.config)
    return ApiResponse(
        message=f"Module '{module_id}' installed and activated on bot",
        data={"module_id": mod.module_id, "is_enabled": mod.is_enabled, "config": mod.config},
    )


@router.post("/{bot_id}/modules/{module_id}/toggle", response_model=ApiResponse[dict[str, Any]], status_code=status.HTTP_200_OK)
async def toggle_bot_module(
    bot_id: UUID,
    module_id: str,
    req: ToggleModuleRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """
    Activates or deactivates a module on the bot.
    Directly controls backend execution of the module's triggers and commands.
    Automatically runs pre-flight verification on activation.
    """
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)
    raw_token = await bot_service.get_raw_token(bot_id)

    mod_service = BotModuleService(db)
    verification_res = None
    if req.is_enabled:
        verification_res = await mod_service.verify_module(
            bot_id=bot_id,
            raw_token=raw_token,
            module_id=module_id,
        )

    mod = await mod_service.toggle_module(bot_id, module_id, is_enabled=req.is_enabled)
    status_str = "activated" if req.is_enabled else "deactivated"
    
    msg = f"Module '{module_id}' {status_str} successfully"
    if verification_res and not verification_res.get("ok"):
        msg = f"Module '{module_id}' activated with verification alert: {verification_res.get('error') or verification_res.get('warning')}"

    return ApiResponse(
        message=msg,
        data={
            "module_id": mod.module_id,
            "is_enabled": mod.is_enabled,
            "verification": verification_res,
        },
    )


@router.patch("/{bot_id}/modules/{module_id}/config", response_model=ApiResponse[dict[str, Any]], status_code=status.HTTP_200_OK)
async def update_bot_module_config(
    bot_id: UUID,
    module_id: str,
    req: UpdateModuleConfigRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Updates configuration parameters for an installed bot module and verifies settings."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)
    raw_token = await bot_service.get_raw_token(bot_id)

    mod_service = BotModuleService(db)
    mod = await mod_service.update_module_config(bot_id, module_id, config=req.config)

    # Run verification on the newly saved config
    verification_res = await mod_service.verify_module(
        bot_id=bot_id,
        raw_token=raw_token,
        module_id=module_id,
        config=mod.config,
    )

    return ApiResponse(
        message=f"Configuration for module '{module_id}' saved successfully",
        data={
            "module_id": mod.module_id,
            "config": mod.config,
            "verification": verification_res,
        },
    )


@router.delete("/{bot_id}/modules/{module_id}", response_model=ApiResponse[None], status_code=status.HTTP_200_OK)
async def uninstall_bot_module(
    bot_id: UUID,
    module_id: str,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Uninstalls a feature module from the bot."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    await mod_service.uninstall_module(bot_id, module_id)
    return ApiResponse(
        message=f"Module '{module_id}' uninstalled successfully",
        data=None,
    )


@router.post("/{bot_id}/modules/verify-admin", response_model=ApiResponse[dict[str, Any]], status_code=status.HTTP_200_OK)
async def verify_bot_channel_admin(
    bot_id: UUID,
    req: VerifyAdminRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """
    Verifies if the bot is added as an Administrator with required rights in a Channel or Group.
    Required by Force Join Guard and Logs & Forum Topics modules.
    """
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)
    raw_token = await bot_service.get_raw_token(bot_id)

    mod_service = BotModuleService(db)
    result = await mod_service.verify_bot_admin(
        bot_id=bot_id,
        raw_token=raw_token,
        chat_id=req.chat_id,
        check_topics=True,
        test_topic=req.test_topic or False,
    )

    msg = result.get("message", "Admin verification check completed")
    return ApiResponse(
        message=msg,
        data=result,
    )


@router.post("/{bot_id}/modules/{module_id}/verify", response_model=ApiResponse[dict[str, Any]], status_code=status.HTTP_200_OK)
async def verify_bot_module(
    bot_id: UUID,
    module_id: str,
    req: VerifyModuleRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """
    Performs comprehensive pre-flight verification on any bot module.
    For logs_tracker and force_join, checks Telegram API bot administrator rights,
    Telegram Forum Topics support, and permissions.
    """
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)
    raw_token = await bot_service.get_raw_token(bot_id)

    mod_service = BotModuleService(db)
    config = req.config
    if req.chat_id:
        if config is None:
            config = await mod_service.get_module_config(bot_id, module_id)
        if module_id == "logs_tracker":
            config["log_channel_id"] = req.chat_id
        elif module_id == "force_join":
            config["channel_username"] = req.chat_id

    result = await mod_service.verify_module(
        bot_id=bot_id,
        raw_token=raw_token,
        module_id=module_id,
        config=config,
        test_topic=req.test_topic or False,
    )
    return ApiResponse(
        message=result.get("message", "Module verification completed"),
        data=result,
    )


# ==============================================================================
# 3-WAY TRIGGER CONTROLS (COMMAND, INLINE BUTTON, MENU BUTTON)
# ==============================================================================

@router.patch("/{bot_id}/modules/{module_id}/triggers", response_model=ApiResponse[dict[str, Any]], status_code=status.HTTP_200_OK)
async def update_module_triggers(
    bot_id: UUID,
    module_id: str,
    req: ToggleModuleTriggerRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """
    Independently controls the 3 interaction triggers for any module:
    1. Command execution (/command)
    2. Callback / inline keyboard button
    3. Persistent reply keyboard menu button
    """
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    mod = await mod_service.toggle_module_triggers(
        bot_id=bot_id,
        module_id=module_id,
        enable_command=req.enable_command,
        enable_inline_button=req.enable_inline_button,
        enable_menu_button=req.enable_menu_button,
    )

    return ApiResponse(
        message=f"Trigger settings for '{module_id}' updated successfully",
        data={
            "module_id": mod.module_id,
            "enable_command": mod.enable_command,
            "enable_inline_button": mod.enable_inline_button,
            "enable_menu_button": mod.enable_menu_button,
        },
    )


# ==============================================================================
# REDEEM CODES & GIFT VOUCHERS MANAGEMENT
# ==============================================================================

@router.post("/{bot_id}/redeem-codes", response_model=ApiResponse[RedeemCodeResponse], status_code=status.HTTP_201_CREATED)
async def create_bot_redeem_code(
    bot_id: UUID,
    req: CreateRedeemCodeRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Generates a promotional gift voucher / redeem code for bot subscribers."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    code_obj = await mod_service.create_redeem_code(
        bot_id=bot_id,
        code=req.code,
        title=req.title,
        reward_type=req.reward_type,
        reward_value=req.reward_value,
        max_uses=req.max_uses,
        expires_at=req.expires_at,
        is_active=req.is_active,
    )
    return ApiResponse(
        message=f"Redeem code '{code_obj.code}' generated successfully",
        data=RedeemCodeResponse.model_validate(code_obj),
    )


@router.get("/{bot_id}/redeem-codes", response_model=ApiResponse[list[RedeemCodeResponse]], status_code=status.HTTP_200_OK)
async def list_bot_redeem_codes(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Lists all active and expired redeem codes configured for this bot."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    codes = await mod_service.list_redeem_codes(bot_id)
    return ApiResponse(
        message="Redeem codes retrieved successfully",
        data=[RedeemCodeResponse.model_validate(c) for c in codes],
    )


@router.get("/{bot_id}/redeem-codes/{code_id}", response_model=ApiResponse[RedeemCodeResponse], status_code=status.HTTP_200_OK)
async def get_bot_redeem_code(
    bot_id: UUID,
    code_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Retrieves full details for a specific redeem code."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    code_obj = await mod_service.get_redeem_code(bot_id, code_id)
    if not code_obj:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Redeem code not found")

    return ApiResponse(
        message="Redeem code retrieved successfully",
        data=RedeemCodeResponse.model_validate(code_obj),
    )


@router.patch("/{bot_id}/redeem-codes/{code_id}", response_model=ApiResponse[RedeemCodeResponse], status_code=status.HTTP_200_OK)
async def update_bot_redeem_code(
    bot_id: UUID,
    code_id: UUID,
    req: UpdateRedeemCodeRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Updates active state, max uses, expiry date, or title of a redeem code."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    updated = await mod_service.update_redeem_code(bot_id, code_id, req.model_dump(exclude_unset=True))
    return ApiResponse(
        message="Redeem code updated successfully",
        data=RedeemCodeResponse.model_validate(updated),
    )


@router.delete("/{bot_id}/redeem-codes/{code_id}", response_model=ApiResponse[None], status_code=status.HTTP_200_OK)
async def delete_bot_redeem_code(
    bot_id: UUID,
    code_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Deletes a redeem code and its associated redemption logs."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    await mod_service.delete_redeem_code(bot_id, code_id)
    return ApiResponse(
        message="Redeem code deleted successfully",
        data=None,
    )


@router.get("/{bot_id}/redeem-codes/{code_id}/logs", response_model=ApiResponse[list[RedeemLogResponse]], status_code=status.HTTP_200_OK)
async def list_code_redemption_logs(
    bot_id: UUID,
    code_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Lists all subscribers who claimed this promotional code."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    logs = await mod_service.list_redeem_logs(bot_id, code_id)
    return ApiResponse(
        message="Redemption audit logs retrieved successfully",
        data=[RedeemLogResponse.model_validate(l) for l in logs],
    )


@router.get("/{bot_id}/files", response_model=ApiResponse[list[BotFileResponse]], status_code=status.HTTP_200_OK)
async def list_bot_files(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Lists all files in the bot's digital file store."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    files = await mod_service.list_bot_files(bot_id)
    return ApiResponse(
        message="Bot digital store files retrieved successfully",
        data=[BotFileResponse.model_validate(f) for f in files],
    )


@router.post("/{bot_id}/files", response_model=ApiResponse[BotFileResponse], status_code=status.HTTP_201_CREATED)
async def create_bot_file(
    bot_id: UUID,
    req: CreateBotFileRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Registers a new file/document in the digital file store."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    bot_file = await mod_service.create_bot_file(
        bot_id=bot_id,
        file_id=req.file_id,
        file_name=req.file_name,
        file_type=req.file_type,
        file_size=req.file_size,
        access_type=req.access_type,
        cost=req.cost,
        unlock_code=req.unlock_code,
    )
    return ApiResponse(
        message="Digital store file registered successfully",
        data=BotFileResponse.model_validate(bot_file),
    )


@router.get("/{bot_id}/support-tickets", response_model=ApiResponse[list[BotSupportTicketResponse]], status_code=status.HTTP_200_OK)
async def list_bot_support_tickets(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Lists all customer support tickets for this bot."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)

    mod_service = BotModuleService(db)
    tickets = await mod_service.list_support_tickets(bot_id)
    return ApiResponse(
        message="Support tickets retrieved successfully",
        data=[BotSupportTicketResponse.model_validate(t) for t in tickets],
    )


@router.post("/{bot_id}/support-tickets/{ticket_id}/reply", response_model=ApiResponse[dict[str, Any]], status_code=status.HTTP_200_OK)
async def reply_bot_support_ticket(
    bot_id: UUID,
    ticket_id: UUID,
    req: ReplySupportTicketRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Sends an administrative support reply to the subscriber on Telegram."""
    tenant, _ = tenant_context
    bot_service = BotService(db)
    await bot_service.get_bot(bot_id, tenant_id=tenant.id)
    raw_token = await bot_service.get_raw_token(bot_id)

    mod_service = BotModuleService(db)
    res = await mod_service.reply_support_ticket(
        bot_id=bot_id,
        ticket_id=ticket_id,
        reply_text=req.reply_text,
        raw_token=raw_token,
    )
    return ApiResponse(
        message="Support ticket reply sent to user successfully",
        data=res,
    )



