from __future__ import annotations

from aiogram import Bot
from sqlalchemy.ext.asyncio import AsyncSession

from app.constants import STATUS_LABELS
from app.models import Booking, Order, User
from app.services.notify import booking_status_text, edit_group_status, order_status_text, safe_send
from app.services.settings import load_settings


async def set_order_status(
    bot: Bot | None,
    session: AsyncSession,
    order_id: int,
    status: str,
    *,
    notify_user: bool = True,
) -> str:
    order = await session.get(Order, order_id)
    if order is None:
        return "missing"
    if order.status == status:
        return "same"
    order.status = status
    settings = await load_settings(session)
    user = await session.get(User, order.user_id)
    if notify_user and bot is not None and user is not None:
        await safe_send(bot, user.telegram_id, order_status_text(order, status, settings))
    label = STATUS_LABELS.get(status, status)
    await edit_group_status(
        bot,
        settings,
        order.group_message_id,
        order.notify_text,
        status,
        f"Замовлення #{order.id}: {label}",
    )
    return "ok"


async def set_booking_status(
    bot: Bot | None,
    session: AsyncSession,
    booking_id: int,
    status: str,
    *,
    notify_user: bool = True,
) -> str:
    booking = await session.get(Booking, booking_id)
    if booking is None:
        return "missing"
    if booking.status == status:
        return "same"
    booking.status = status
    settings = await load_settings(session)
    user = await session.get(User, booking.user_id)
    if notify_user and bot is not None and user is not None:
        await safe_send(
            bot,
            user.telegram_id,
            booking_status_text(booking, status, settings, user.language or "uk"),
        )
    label = STATUS_LABELS.get(status, status)
    await edit_group_status(
        bot,
        settings,
        booking.group_message_id,
        booking.notify_text,
        status,
        f"Бронювання #{booking.id}: {label}",
    )
    return "ok"
