from odoo import http
from odoo.http import request
import json
import logging

_logger = logging.getLogger(__name__)

class UberWebhookController(http.Controller):

    @http.route('/uber/webhook/delivery', type='json', auth='none', methods=['POST'], csrf=False)
    def uber_delivery_webhook(self, **post):
        """Handle status updates from Uber Direct"""
        data = json.loads(request.httprequest.data)
        _logger.info("Uber Webhook Received: %s", json.dumps(data, indent=2))
        
        uber_delivery_id = data.get('delivery_id')
        status = data.get('status') # e.g., 'picked_up', 'delivered'
        
        if uber_delivery_id:
            order = request.env['pos.order'].sudo().search([('uber_delivery_id', '=', uber_delivery_id)], limit=1)
            if order:
                # Map Uber status to Odoo status
                status_map = {
                    'pickup': 'pickup',
                    'pickup_completed': 'delivering',
                    'dropoff_completed': 'delivered',
                    'cancelled': 'cancelled'
                }
                order.uber_status = status_map.get(status, order.uber_status)
                return {'status': 'success'}
                
        return {'status': 'ignored'}
