-- Migration Script für bestehende Lizenzen
-- Setzt Default-Werte für Resource Counts
-- Stand: 2025-06-09

-- ====================================
-- Prüfe ob Migration notwendig ist
-- ====================================
DO $$
DECLARE
    licenses_without_resources INT;
    total_licenses INT;
BEGIN
    -- Zähle Lizenzen ohne Resource-Count Werte
    SELECT COUNT(*) INTO licenses_without_resources 
    FROM licenses 
    WHERE domain_count IS NULL 
       OR ipv4_count IS NULL 
       OR phone_count IS NULL;
    
    SELECT COUNT(*) INTO total_licenses FROM licenses;
    
    IF licenses_without_resources > 0 THEN
        RAISE NOTICE 'Migration notwendig für % von % Lizenzen', licenses_without_resources, total_licenses;
    ELSE
        RAISE NOTICE 'Keine Migration notwendig - alle Lizenzen haben bereits Resource Counts';
        RETURN;
    END IF;
END $$;

-- ====================================
-- Setze Default Resource Counts
-- ====================================

-- Vollversionen erhalten standardmäßig je 2 Ressourcen
UPDATE licenses 
SET domain_count = COALESCE(domain_count, 2),
    ipv4_count = COALESCE(ipv4_count, 2),
    phone_count = COALESCE(phone_count, 2)
WHERE license_type = 'full'
  AND (domain_count IS NULL OR ipv4_count IS NULL OR phone_count IS NULL);

-- Testversionen erhalten standardmäßig je 1 Ressource
UPDATE licenses 
SET domain_count = COALESCE(domain_count, 1),
    ipv4_count = COALESCE(ipv4_count, 1),
    phone_count = COALESCE(phone_count, 1)
WHERE license_type = 'test'
  AND (domain_count IS NULL OR ipv4_count IS NULL OR phone_count IS NULL);

-- Inaktive Lizenzen erhalten 0 Ressourcen
UPDATE licenses 
SET domain_count = COALESCE(domain_count, 0),
    ipv4_count = COALESCE(ipv4_count, 0),
    phone_count = COALESCE(phone_count, 0)
WHERE is_active = FALSE
  AND (domain_count IS NULL OR ipv4_count IS NULL OR phone_count IS NULL);

-- ====================================
-- Erstelle Resource-Zuweisungen für bestehende aktive Lizenzen
-- ====================================
DO $$
DECLARE
    license_rec RECORD;
    resource_rec RECORD;
    resources_assigned INT := 0;
    resources_needed INT;
BEGIN
    -- Durchlaufe alle aktiven Lizenzen mit Resource Counts > 0
    FOR license_rec IN 
        SELECT id, domain_count, ipv4_count, phone_count 
        FROM licenses 
        WHERE is_active = TRUE 
          AND (domain_count > 0 OR ipv4_count > 0 OR phone_count > 0)
        ORDER BY created_at
    LOOP
        -- Domains zuweisen
        resources_needed := license_rec.domain_count;
        FOR i IN 1..resources_needed LOOP
            -- Finde eine verfügbare Domain
            SELECT id INTO resource_rec 
            FROM resource_pools 
            WHERE resource_type = 'domain' 
              AND status = 'available'
            ORDER BY RANDOM()
            LIMIT 1;
            
            IF resource_rec.id IS NOT NULL THEN
                -- Weise Resource zu
                UPDATE resource_pools 
                SET status = 'allocated',
                    allocated_to_license = license_rec.id,
                    status_changed_at = NOW(),
                    status_changed_by = 'migration'
                WHERE id = resource_rec.id;
                
                -- Erstelle Zuordnung
                INSERT INTO license_resources (license_id, resource_id, assigned_by)
                VALUES (license_rec.id, resource_rec.id, 'migration');
                
                -- Historie eintragen
                INSERT INTO resource_history (resource_id, license_id, action, action_by, details)
                VALUES (resource_rec.id, license_rec.id, 'allocated', 'migration', 
                       '{"reason": "Migration bestehender Lizenzen"}'::jsonb);
                
                resources_assigned := resources_assigned + 1;
            END IF;
        END LOOP;
        
        -- IPv4-Adressen zuweisen
        resources_needed := license_rec.ipv4_count;
        FOR i IN 1..resources_needed LOOP
            SELECT id INTO resource_rec 
            FROM resource_pools 
            WHERE resource_type = 'ipv4' 
              AND status = 'available'
            ORDER BY RANDOM()
            LIMIT 1;
            
            IF resource_rec.id IS NOT NULL THEN
                UPDATE resource_pools 
                SET status = 'allocated',
                    allocated_to_license = license_rec.id,
                    status_changed_at = NOW(),
                    status_changed_by = 'migration'
                WHERE id = resource_rec.id;
                
                INSERT INTO license_resources (license_id, resource_id, assigned_by)
                VALUES (license_rec.id, resource_rec.id, 'migration');
                
                INSERT INTO resource_history (resource_id, license_id, action, action_by, details)
                VALUES (resource_rec.id, license_rec.id, 'allocated', 'migration', 
                       '{"reason": "Migration bestehender Lizenzen"}'::jsonb);
                
                resources_assigned := resources_assigned + 1;
            END IF;
        END LOOP;
        
        -- Telefonnummern zuweisen
        resources_needed := license_rec.phone_count;
        FOR i IN 1..resources_needed LOOP
            SELECT id INTO resource_rec 
            FROM resource_pools 
            WHERE resource_type = 'phone' 
              AND status = 'available'
            ORDER BY RANDOM()
            LIMIT 1;
            
            IF resource_rec.id IS NOT NULL THEN
                UPDATE resource_pools 
                SET status = 'allocated',
                    allocated_to_license = license_rec.id,
                    status_changed_at = NOW(),
                    status_changed_by = 'migration'
                WHERE id = resource_rec.id;
                
                INSERT INTO license_resources (license_id, resource_id, assigned_by)
                VALUES (license_rec.id, resource_rec.id, 'migration');
                
                INSERT INTO resource_history (resource_id, license_id, action, action_by, details)
                VALUES (resource_rec.id, license_rec.id, 'allocated', 'migration', 
                       '{"reason": "Migration bestehender Lizenzen"}'::jsonb);
                
                resources_assigned := resources_assigned + 1;
            END IF;
        END LOOP;
    END LOOP;
    
    RAISE NOTICE 'Migration abgeschlossen: % Ressourcen wurden zugewiesen', resources_assigned;
END $$;

-- ====================================
-- Abschlussbericht
-- ====================================
DO $$
DECLARE
    v_total_licenses INT;
    v_licenses_with_resources INT;
    v_total_resources_assigned INT;
    v_domains_assigned INT;
    v_ipv4_assigned INT;
    v_phones_assigned INT;
BEGIN
    -- Statistiken sammeln
    SELECT COUNT(*) INTO v_total_licenses FROM licenses;
    
    SELECT COUNT(*) INTO v_licenses_with_resources 
    FROM licenses 
    WHERE id IN (SELECT DISTINCT license_id FROM license_resources WHERE is_active = TRUE);
    
    SELECT COUNT(*) INTO v_total_resources_assigned 
    FROM license_resources 
    WHERE is_active = TRUE;
    
    SELECT COUNT(*) INTO v_domains_assigned 
    FROM resource_pools 
    WHERE resource_type = 'domain' AND status = 'allocated';
    
    SELECT COUNT(*) INTO v_ipv4_assigned 
    FROM resource_pools 
    WHERE resource_type = 'ipv4' AND status = 'allocated';
    
    SELECT COUNT(*) INTO v_phones_assigned 
    FROM resource_pools 
    WHERE resource_type = 'phone' AND status = 'allocated';
    
    -- Bericht ausgeben
    RAISE NOTICE '';
    RAISE NOTICE '========================================';
    RAISE NOTICE 'MIGRATION ABGESCHLOSSEN';
    RAISE NOTICE '========================================';
    RAISE NOTICE 'Lizenzen gesamt: %', v_total_licenses;
    RAISE NOTICE 'Lizenzen mit Ressourcen: %', v_licenses_with_resources;
    RAISE NOTICE '';
    RAISE NOTICE 'Zugewiesene Ressourcen:';
    RAISE NOTICE '- Domains: %', v_domains_assigned;
    RAISE NOTICE '- IPv4-Adressen: %', v_ipv4_assigned;
    RAISE NOTICE '- Telefonnummern: %', v_phones_assigned;
    RAISE NOTICE '- Gesamt: %', v_total_resources_assigned;
    RAISE NOTICE '========================================';
    
    -- Warnungen ausgeben
    IF EXISTS (
        SELECT 1 FROM licenses l
        WHERE l.is_active = TRUE 
        AND (l.domain_count > 0 OR l.ipv4_count > 0 OR l.phone_count > 0)
        AND NOT EXISTS (
            SELECT 1 FROM license_resources lr 
            WHERE lr.license_id = l.id AND lr.is_active = TRUE
        )
    ) THEN
        RAISE WARNING 'ACHTUNG: Einige aktive Lizenzen konnten keine Ressourcen erhalten (möglicherweise nicht genug verfügbar)';
        
        -- Liste betroffene Lizenzen auf
        FOR v_total_licenses IN 
            SELECT l.id FROM licenses l
            WHERE l.is_active = TRUE 
            AND (l.domain_count > 0 OR l.ipv4_count > 0 OR l.phone_count > 0)
            AND NOT EXISTS (
                SELECT 1 FROM license_resources lr 
                WHERE lr.license_id = l.id AND lr.is_active = TRUE
            )
        LOOP
            RAISE WARNING 'Lizenz ID % hat keine Ressourcen erhalten', v_total_licenses;
        END LOOP;
    END IF;
END $$;

-- ====================================
-- Audit Log Eintrag für Migration
-- ====================================
INSERT INTO audit_log (
    timestamp,
    username,
    action,
    entity_type,
    additional_info
) VALUES (
    NOW(),
    'system',
    'MIGRATION',
    'licenses',
    'Resource Pool Migration für bestehende Lizenzen durchgeführt'
);