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'}
    


class UberDeliveryController(http.Controller):

    @http.route('/shop/uber/quote', type='json', auth='public', website=True, csrf=False)
    def uber_quote(self, address_data, **post):
        """Get Uber quote for a website address"""
        order = request.website.sale_get_order()
        if not order:
            return {'success': False, 'error': 'No active order'}

        config = request.env['uber.config'].sudo().search([('active', '=', True)], limit=1)
        if not config:
            return {'success': False, 'error': 'Uber not configured'}

        company = request.website.company_id
        pickup_address = f"{company.street}, {company.city}, {company.zip}, {company.country_id.name}"
        
        # User entered address
        dropoff_address = f"{address_data.get('street')}, {address_data.get('city')}, {address_data.get('zip')}, {address_data.get('country')}"

        result = config.get_uber_quote(pickup_address, dropoff_address)
        
        if result.get('success'):
            # Clear old delivery fee if different? Or just update.
            # In Odoo website_sale, we usually want to add it to the cart
            order.sudo()._add_uber_delivery_fee(result['fee_amount'])
            return {
                'success': True,
                'fee': result['fee_amount'],
                'eta': result.get('estimated_arrival'),
            }
        else:
            return result
