#!/usr/bin/env python3
"""
Vereinfachter Test: Erstelle Dokument und CAICollection über API und teste Verknüpfung
"""

import requests
import json
import sys
from datetime import datetime

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

def api_request(method, endpoint, data=None):
    """API-Request"""
    url = f"{BASE_URL}/api/v1/{endpoint}"
    try:
        if method == "GET":
            response = requests.get(url, headers=HEADERS)
        elif method == "POST":
            response = requests.post(url, headers=HEADERS, json=data)
        elif method == "DELETE":
            response = requests.delete(url, headers=HEADERS)
        
        print(f"  {method} {endpoint} -> Status: {response.status_code}")
        
        if response.status_code >= 400:
            print(f"  Error Response: {response.text[:200]}")
            return None
            
        return response.json() if response.text else {}
    except Exception as e:
        print(f"  Exception: {e}")
        return None

print("\n" + "="*80)
print(" "*25 + "Junction API Test - Simplified")
print("="*80 + "\n")

doc_id = None
collection_id = None
test_sync_id = f"SYNC-{datetime.now().strftime('%Y%m%d-%H%M%S')}"

try:
    # 1. CDokumente erstellen
    print("1️⃣  Erstelle CDokumente...")
    doc = api_request("POST", "CDokumente", {
        "name": f"API-Test Dokument {datetime.now().strftime('%H:%M:%S')}",
        "description": "Für Junction-Test"
    })
    
    if doc and 'id' in doc:
        doc_id = doc['id']
        print(f"  ✓ Dokument erstellt: {doc_id}\n")
    else:
        print("  ❌ Fehler\n")
        sys.exit(1)
    
    # 2. Versuche CAICollection zu erstellen (könnte fehlschlagen wegen Berechtigungen)
    print("2️⃣  Versuche CAICollection zu erstellen...")
    collection = api_request("POST", "CAICollections", {
        "name": f"API-Test Collection {datetime.now().strftime('%H:%M:%S')}",
        "description": "Für Junction-Test"
    })
    
    if collection and 'id' in collection:
        collection_id = collection['id']
        print(f"  ✓ Collection erstellt: {collection_id}\n")
        
        # 3. Verknüpfen mit syncId
        print("3️⃣  Verknüpfe mit syncId...")
        print(f"  syncId: {test_sync_id}")
        join_result = api_request("POST", f"CDokumente/{doc_id}/cAICollections", {
            "id": collection_id,
            "columns": {
                "syncId": test_sync_id
            }
        })
        print(f"  Join Result: {join_result}\n")
        
        # 4. Abrufen
        print("4️⃣  Rufe Beziehung ab...")
        relations = api_request("GET", f"CDokumente/{doc_id}/cAICollections")
        
        if relations:
            print(f"\nAPI Response:")
            print(json.dumps(relations, indent=2, ensure_ascii=False))
            print()
            
            if 'list' in relations and len(relations['list']) > 0:
                first = relations['list'][0]
                if 'syncId' in first:
                    print(f"✅ syncId gefunden in API: {first['syncId']}")
                    if first['syncId'] == test_sync_id:
                        print(f"✅ syncId-Wert stimmt überein!")
                    else:
                        print(f"⚠️  Wert stimmt nicht: {first['syncId']} != {test_sync_id}")
                else:
                    print(f"❌ syncId NICHT in Response (Felder: {list(first.keys())})")
            else:
                print("❌ Keine Relation gefunden")
        
    else:
        print("  ❌ Keine Berechtigung für CAICollections\n")
        print("  ℹ️  Das ist ein Berechtigungsproblem, kein Problem mit den additionalColumns\n")
        
finally:
    print("\n5️⃣  Cleanup...")
    if doc_id:
        api_request("DELETE", f"CDokumente/{doc_id}")
        print(f"  ✓ Dokument gelöscht")
    if collection_id:
        api_request("DELETE", f"CAICollections/{collection_id}")
        print(f"  ✓ Collection gelöscht")

print("\n" + "="*80 + "\n")
