# === ENDPOINT VALIDATION DE LICENCE ===

@app.route('/api/v1/license/verify', methods=['POST'])
def verify_license():
    """Vérifier une licence utilisateur via PostgreSQL."""
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "JSON body required"}), 400
        
        email = data.get('email', '').lower().strip()
        tier = data.get('tier', '').lower()
        
        if not email or not tier:
            return jsonify({"error": "email and tier required"}), 400
        
        # Validation via PostgreSQL
        try:
            import psycopg2
            db_url = os.getenv('DATABASE_URL', 'postgresql://websentinel_user:WebSentinel2025SecureDB!@web-sentinel-db:5432/websentinel_prod')
            
            with psycopg2.connect(db_url) as conn:
                with conn.cursor() as cursor:
                    cursor.execute("""
                        SELECT tier, created_at, last_used, is_active, daily_limit, monthly_limit, key_hash
                        FROM api_key 
                        WHERE email = %s AND is_active = TRUE
                    """, (email,))
                    
                    row = cursor.fetchone()
                    
            if not row:
                return jsonify({
                    "valid": False,
                    "reason": f"No active subscription found for {email}"
                }), 404
            
            db_tier, created_at, last_used, is_active, daily_limit, monthly_limit, key_hash = row
            
            # Vérifier la cohérence du tier  
            if db_tier and db_tier.lower() != tier:
                return jsonify({
                    "valid": False,
                    "reason": f"Tier mismatch: requested={tier}, database={db_tier}"
                }), 400
            
            # Mettre à jour last_used
            try:
                with psycopg2.connect(db_url) as conn:
                    with conn.cursor() as cursor:
                        cursor.execute("""
                            UPDATE api_key 
                            SET last_used = NOW()
                            WHERE email = %s
                        """, (email,))
                        conn.commit()
            except:
                pass  # Non critique
            
            return jsonify({
                "valid": True,
                "tier": db_tier,
                "limits": {
                    "daily": daily_limit,
                    "monthly": monthly_limit
                },
                "metadata": {
                    "created_at": created_at.isoformat() if created_at else None,
                    "last_used": datetime.utcnow().isoformat() + "Z"
                }
            })
                        
        except ImportError:
            return jsonify({"error": "PostgreSQL driver not available"}), 500
        except Exception as db_error:
            return jsonify({"error": f"Database error: {str(db_error)}"}), 500
            
    except Exception as e:
        return jsonify({"error": f"License verification failed: {str(e)}"}), 500