from db.helpers import get_engine
from sqlalchemy.orm import Session
from db.models import TrayWebhook
import json
import logging
from service.tray_order_service import TrayOrderService

logger = logging.getLogger(__name__)



def process_webhook(body: dict):
    save_webhook(body)
    act = body['act']
    order_id = body['scope_id']
    seller_id = body['seller_id']
    
    if seller_id != "1018776":
        logger.info(f"seller_id: {seller_id}. Exiting.")
        return 400
    
    order_service = TrayOrderService()
    
    if act == 'insert' or act == 'update':
       order = order_service.get_complete_order(order_id)       
       logger.info(order)
       return order
        
    return 400
        
def save_webhook(body: dict):
    with Session(get_engine()) as session:
        webhook = TrayWebhook(json.dumps(body))
        session.add(webhook)
        session.commit()
        
        