from ..queries import query_data_as_dict,query_data,derive_timestamp
def fetch_filtered_transactions_paginated(
    sol_amount, 
    operator=">",
    timestamp_operator=None, 
    limit=200, 
    offset=0,
    years=0,
    months=0,
    weeks=0,
    days=0,
    hours=0,
    minutes=0,
    seconds=0,
    timestamp=None,
    *args,
    **kwargs
):
    query = f"""
        SELECT
            p.*, 
            m.*,
            t.*
        FROM 
            transactions t
        JOIN 
            pairs p ON t.pair_id = p.id
        LEFT JOIN 
            metadata m ON p.meta_id = m.id
        WHERE 
            t.signature IN (
                SELECT signature FROM pairs WHERE signature IS NOT NULL
            )
        AND 
            t.program_id = p.program_id
        AND 
            EXISTS (
                SELECT 1
                FROM jsonb_array_elements(t.tcns) AS elem
                WHERE (elem ->> 'sol_amount')::numeric {operator} %s
    """
    params = [sol_amount]

    ts = derive_timestamp(
            years=years,
            months=months,
            weeks=weeks,
            days=days,
            hours=hours,
            minutes=minutes,
            seconds=seconds,
            timestamp=timestamp)
    
    if ts and timestamp_operator:
        query += f" AND (elem ->> 'timestamp')::bigint {timestamp_operator} %s"
        params.append(int(ts))
    
    query += ") ORDER BY t.updated_at DESC LIMIT %s OFFSET %s;"
    params.extend([limit, offset])
    
    return query_data_as_dict(query, params)

