import requests

# =========== RELLENA TUS DATOS ===========
TENANT_ID = "b16d289b-fa4c-4578-accd-b308f19bbeb5"
CLIENT_ID = "9956717e-890f-4c61-864a-363ae9e025a9"
CLIENT_SECRET = "OZSBa5Dl9GJkoksoPAvzwwsfC2vHDQuadt"
ENVIRONMENT = "igsacrm"  # O tu entorno real
SCOPE = "https://api.businesscentral.dynamics.com/.default"
# ==========================================

TOKEN_URL = f"https://login.microsoftonline.com/b16d289b-fa4c-4578-accd-b308f19bbeb5/oauth2/v2.0/token"

# Paso 1: Obtener token
data = {
    "grant_type": "client_credentials",
    "client_id": CLIENT_ID,
    "client_secret": CLIENT_SECRET,
    "scope": SCOPE,
}

try:
    token_response = requests.post(TOKEN_URL, data=data)
    token_response.raise_for_status()
    access_token = token_response.json()["access_token"]
    print("✅ Token obtenido.")

    # Paso 2: Obtener lista de compañías
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json"
    }
    companies_url = f"https://api.businesscentral.dynamics.com/v2.0/{TENANT_ID}/{ENVIRONMENT}/api/v2.0/companies"
    companies_response = requests.get(companies_url, headers=headers)
    companies_response.raise_for_status()
    companies = companies_response.json()["value"]
    print(f"Compañías encontradas: {len(companies)}")
    for c in companies:
        print(f"- {c['name']} ({c['id']})")
    
    # Paso 3: Consultar clientes de la primera compañía
    if companies:
        company_id = companies[0]["id"]
        customers_url = f"https://api.businesscentral.dynamics.com/v2.0/{TENANT_ID}/{ENVIRONMENT}/api/v2.0/companies({company_id})/customers"
        customers_response = requests.get(customers_url, headers=headers)
        customers_response.raise_for_status()
        customers = customers_response.json()["value"]
        print(f"\nClientes encontrados: {len(customers)}")
        for cust in customers:
            print(f"- {cust['displayName']} (ID: {cust['id']})")
    else:
        print("No se encontraron compañías disponibles.")
except Exception as e:
    print("Error durante la prueba:", e)
