#!/usr/bin/env python3
"""
Finaler Test: Junction-Entity API mit Filterung und syncId
"""

import requests
import json

BASE_URL = "https://crm.bitbylaw.com"
API_KEY = "e53def10eea27b92a6cd00f40a3e09a4"
HEADERS = {
    "X-Api-Key": API_KEY,
    "Content-Type": "application/json"
}

print("\n" + "="*80)
print(" "*25 + "Junction-Entity API - SUCCESS!")
print("="*80 + "\n")

# Test 1: Alle Junction-Einträge
print("1️⃣  Alle Verknüpfungen abrufen:")
response = requests.get(
    f"{BASE_URL}/api/v1/CAICollectionCDokumente",
    headers=HEADERS,
    params={"maxSize": 10}
)
print(f"   Status: {response.status_code}")
data = response.json()
print(f"   Total: {data['total']}")
print(f"   ✅ API funktioniert!\n")

# Test 2: Filterung nach Dokument-ID
print("2️⃣  Filterung nach Dokument-ID (testdoc999):")
response = requests.get(
    f"{BASE_URL}/api/v1/CAICollectionCDokumente",
    headers=HEADERS,
    params={
        "where[0][type]": "equals",
        "where[0][attribute]": "cDokumenteId",
        "where[0][value]": "testdoc999",
        "select": "id,cDokumenteId,cAICollectionsId,syncId"
    }
)
print(f"   Status: {response.status_code}")
if response.status_code == 200:
    data = response.json()
    print(json.dumps(data, indent=2, ensure_ascii=False))
    
    if data['list'] and 'syncId' in data['list'][0]:
        print(f"\n   ✅ syncId gefunden: {data['list'][0]['syncId']}")
print()

# Test 3: Suche nach syncId
print("3️⃣  Filterung nach syncId (SYNC-TEST-999):")
response = requests.get(
    f"{BASE_URL}/api/v1/CAICollectionCDokumente",
    headers=HEADERS,
    params={
        "where[0][type]": "equals",
        "where[0][attribute]": "syncId",
        "where[0][value]": "SYNC-TEST-999"
    }
)
print(f"   Status: {response.status_code}")
if response.status_code == 200:
    data = response.json()
    print(json.dumps(data, indent=2, ensure_ascii=False))
    if data['list']:
        entry = data['list'][0]
        print(f"\n   ✅ Verknüpfung gefunden:")
        print(f"      Dokument: {entry['cDokumenteId']}")
        print(f"      Collection: {entry['cAICollectionsId']}")
        print(f"      Sync-ID: {entry['syncId']}")
print()

print("="*80)
print("✅ VOLLSTÄNDIGER ERFOLG!")
print("="*80)
print("\nDie Junction-Entity ist via REST-API verfügbar und gibt die syncId zurück!")
print("- Endpoint: /api/v1/CAICollectionCDokumente")
print("- Filterung funktioniert (where-Clauses)")
print("- Alle additionalColumns (syncId) sind in der Response")
print("\n" + "="*80 + "\n")
