from flask import Flask
from telebot import TeleBot, logger
from telebot.types import Message
from app.bot.constants import UserStates
from app.bot.keyboards.settings_menu import get_settings_menu
from app.bot.states import UserStateManager
from app.bot.utils.auth import auth
from app.models import Regions, Subscriptions
from app.bot.utils.regions import format_regions_list

def handle_my_subscriptions(message: Message, bot: TeleBot, app: Flask, state_manager: UserStateManager):
    chat_id = message.chat.id
    username = f"{message.from_user.username}" if message.from_user.username else "N/A"
    if not auth(chat_id, app):
        bot.send_message(chat_id, "❌Вы не авторизованы для использования этого бота.")
        logger.warning(f"Неавторизованный пользователь {chat_id} @{username}")
        state_manager.set_state(chat_id, UserStates.REGISTRATION)
        return

    with app.app_context():
        user_regions = (
            Regions.query
            .with_entities(Regions.region_id, Regions.region_name)
            .join(Subscriptions, Subscriptions.region_id == Regions.region_id)
            .filter(
                Subscriptions.chat_id == chat_id,
                Subscriptions.active == True,
                Subscriptions.skip == False
            )
            .order_by(Regions.region_id.asc())
            .all()
        )

    if not user_regions:
        bot.send_message(chat_id, "ℹ️Вы не подписаны ни на один регион.", reply_markup=get_settings_menu())
    else:
        regions_list = format_regions_list(user_regions)
        bot.send_message(chat_id, f"ℹ️Ваши активные подписки:\n{regions_list}", reply_markup=get_settings_menu())

