import jwt
import time

from utils import logger, requestGET


def generate_token(identity: str, secret: str):

    iat = int(time.time())
    exp = iat + 60  # <= 64 сек

    payload = {"iss": identity, "iat": iat, "exp": exp}

    token = jwt.encode(payload, secret, algorithm="HS512")

    return token


async def checkConnection(host: str, port: int, bearerToken: str):
    headers = {"Authorization": f"Bearer {bearerToken}"}
    params = {
        "limit": 1,
        "offset": 0,
    }
    return await requestGET(
        f"http://{host}:{port}/api/v2/clinics",
        headers=headers,
        params=params,
        verify_ssl=False,
    )


async def getAllEmployees(host: str, port: int, identity: str, secret: str):
    bearerToken = generate_token(identity, secret)
    headers = {"Authorization": f"Bearer {bearerToken}"}

    limit = 100
    offset = 0
    employees: list[dict] = []

    while True:
        params = {
            "limit": limit,
            "offset": offset,
        }

        response = await requestGET(
            f"http://{host}:{port}/api/v2/users",
            headers=headers,
            params=params,
            verify_ssl=False,
        )

        # 🔴 Ошибка запроса
        if not response.success:
            logger.error(response.message)
            return employees

        payload = response.data or {}
        batch = payload.get("data", [])
        total_items = payload.get("totalItems", 0)

        employees.extend(batch)

        # 🛑 если получили всё — выходим
        if offset + limit >= total_items:
            break

        offset += limit

    return employees
