import asyncio

from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger

from app import mongo
from app.providers import tinkoff
from app.utils.logger_util import logger

scheduler = AsyncIOScheduler()


async def start():
    scheduler.start()
    scheduler.add_job(
        check_bills,
        trigger=IntervalTrigger(minutes=1),
        name="Check bill status every hour"
    )


async def check_bills():
    deals = await mongo.deals_collection.find({}, {"_id": False}).to_list(length=None)
    for deal in deals:
        bill_request = deal.get("billRequest")
        if bill_request and not bill_request.get("paid"):
            status = await tinkoff.get_bill_status(bill_request["invoiceId"])
            if status == "EXECUTED":
                bill_request["paid"] = True
                await mongo.deals_collection.update_one(
                    {"id": deal["id"]},
                    {"$set": {"billRequest": bill_request}}
                )

                logger.info(f"Updated bill status for deal {deal['id']}")
