from database.connection import get_db


async def find_by_phone(phone: str) -> dict | None:
    """Найти запись в белом списке по нормализованному номеру."""
    db = get_db()
    async with db.execute(
        "SELECT * FROM org_users WHERE phone = ?", (phone,)
    ) as cur:
        row = await cur.fetchone()
    return dict(row) if row else None


async def get_org_users(org_id: int | None = None) -> list[dict]:
    db = get_db()
    if org_id is not None:
        async with db.execute(
            "SELECT ou.*, o.name as org_name FROM org_users ou "
            "JOIN organizations o ON o.id = ou.org_id "
            "WHERE ou.org_id = ? ORDER BY ou.display_name",
            (org_id,),
        ) as cur:
            rows = await cur.fetchall()
    else:
        async with db.execute(
            "SELECT ou.*, o.name as org_name FROM org_users ou "
            "JOIN organizations o ON o.id = ou.org_id "
            "ORDER BY o.name, ou.display_name"
        ) as cur:
            rows = await cur.fetchall()
    return [dict(r) for r in rows]


async def create_org_user(org_id: int, phone: str, display_name: str | None) -> int:
    db = get_db()
    async with db.execute(
        "INSERT INTO org_users (org_id, phone, display_name) VALUES (?, ?, ?)",
        (org_id, phone, display_name),
    ) as cur:
        row_id = cur.lastrowid
    await db.commit()
    return row_id


async def delete_org_user(user_id: int) -> None:
    db = get_db()
    await db.execute("DELETE FROM org_users WHERE id = ?", (user_id,))
    await db.commit()
