from aiogram.types import Message
from aiogram.filters import Command, CommandStart, CommandObject
from aiogram import Router, F
from aiogram.utils.i18n import gettext as _
from keyboards import inline
from models.admin import Admin
from models.user import User
from config import send_to_admins

router = Router()

@router.message(CommandStart())
async def command_start_handler(message: Message, command: CommandObject, user_model: User, admin_model: Admin) -> Message:
    referred_id = None
    hyperlink = None

    if command.args:
        try:
            if command.args.isdigit():
                referred_id = int(command.args)
            else:
                hyperlink = str(command.args)
        except ValueError:
            pass

    if hyperlink:
        hyperlink_info: dict = await admin_model.get_hyperlink(hyperlink)
        if hyperlink_info is not None:
            is_user_exits: bool = await admin_model.is_hyperlink_user_exits(message.from_user.id, hyperlink_info["id"])
            if not is_user_exits:
                await admin_model.create_hyperlink_user(message.from_user.id, message.from_user.username, hyperlink_info["id"])
                await admin_model.update_hyperlink(hyperlink_info["id"], 'counts', hyperlink_info["counts"] + 1)

    user_info: dict = await user_model.get_by_user_id(message.from_user.id)

    if user_info is None:
        if referred_id:
            await user_model.create(message.from_user.id, message.from_user.username, message.from_user.language_code, referred_id=referred_id)
            referred_info: dict = await user_model.get_by_user_id(referred_id)
            await user_model.update_user(referred_id, 'referral_counts', int(referred_info["referral_counts"]) + 1)
            await message.bot.send_message(referred_id, _("common.referral_invite.message").format(
                referral_id=message.from_user.id))
        else:
            await user_model.create(message.from_user.id, message.from_user.username, message.from_user.language_code)

        # User created notification sent below

        await send_to_admins(message.bot, f'<b>ℹ️Новый пользователь {message.from_user.id}</b> @{message.from_user.username}')
        user_info: dict = await user_model.get_by_user_id(message.from_user.id)

    orders = await admin_model.get_orders_by_user_id(message.from_user.id)
    subs_list = await admin_model.get_subscriptions_user(message.from_user.id)

    await message.answer(_("common.welcome.message").format(username= user_info["username"],
                        user_id=message.from_user.id,
                        plans_count=len(subs_list),
                        orders_count=len(orders),
                        date=user_info["created_at"]),
                        reply_markup=inline.start_menu())

