from __future__ import annotations

from aiogram.types import User as TgUser
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models import ResellerBot, ResellerCustomer

RESELLER_SHARE = 0.75
MIN_PAYOUT = 3.0


def reseller_price(base_price: float, markup_percent: float) -> float:
    return round(float(base_price) * (1 + max(0.0, float(markup_percent)) / 100), 2)


def reseller_profit(base_price: float, final_price: float) -> tuple[float, float]:
    margin = max(0.0, round(float(final_price) - float(base_price), 2))
    reseller = round(margin * RESELLER_SHARE, 2)
    platform = round(margin - reseller, 2)
    return reseller, platform


async def record_customer(
    session: AsyncSession, reseller_id: int, tg_user: TgUser
) -> None:
    result = await session.execute(
        select(ResellerCustomer).where(
            ResellerCustomer.reseller_id == reseller_id,
            ResellerCustomer.user_id == tg_user.id,
        )
    )
    row = result.scalar_one_or_none()
    if row is None:
        session.add(
            ResellerCustomer(
                reseller_id=reseller_id,
                user_id=tg_user.id,
                username=tg_user.username or "",
                full_name=tg_user.full_name or "",
            )
        )
        await session.commit()
        return
    changed = False
    if row.username != (tg_user.username or ""):
        row.username = tg_user.username or ""
        changed = True
    if row.full_name != (tg_user.full_name or ""):
        row.full_name = tg_user.full_name or ""
        changed = True
    if changed:
        await session.commit()


async def get_active_reseller(
    session: AsyncSession, reseller_id: int
) -> ResellerBot | None:
    reseller = await session.get(ResellerBot, reseller_id)
    if reseller is None or not reseller.is_active:
        return None
    return reseller
