from odoo import http
from odoo.http import request
from odoo.addons.website_sale.controllers.main import WebsiteSale

class Dine360OnlineOrders(http.Controller):

    @http.route('/shop/update_service_mode', type='json', auth="public", website=True)
    def update_service_mode(self, service_mode, **post):
        order = request.website.sale_get_order()
        if order and service_mode in ['pickup', 'delivery', 'dine_in']:
            order.sudo().write({
                'fulfilment_type': service_mode,
                'order_source': 'online'
            })
        return True

class Dine360WebsiteSaleOnline(WebsiteSale):
    @http.route(['/shop/payment'], type='http', auth="public", website=True, sitemap=False)
    def shop_payment(self, **post):
        order = request.website.sale_get_order()
        if order and not order.carrier_id:
            # Bypass delivery validation by assigning the first available delivery carrier
            carriers = order._get_delivery_methods()
            if not carriers:
                carriers = request.env['delivery.carrier'].sudo().search([('is_published', '=', True)], limit=1)
            
            if carriers:
                order.carrier_id = carriers[0].id
                price = carriers[0].rate_shipment(order)['price'] if hasattr(carriers[0], 'rate_shipment') and order._get_delivery_methods() else 0.0
                order.set_delivery_line(carriers[0], price)

        return super(Dine360WebsiteSaleOnline, self).shop_payment(**post)

    @http.route('/shop/payment/transaction/<int:order_id>', type='json', auth="public", website=True)
    def shop_payment_transaction(self, order_id, access_token=None, **kwargs):
        # Force bypass "No shipping method is selected" error during payment processing
        order = request.env['sale.order'].sudo().browse(order_id)
        if order and not order.carrier_id:
            carriers = request.env['delivery.carrier'].sudo().search([('is_published', '=', True)], limit=1)
            if carriers:
                order.carrier_id = carriers[0].id
                order.set_delivery_line(carriers[0], 0.0)
        return super(Dine360WebsiteSaleOnline, self).shop_payment_transaction(order_id, access_token=access_token, **kwargs)

    @http.route(['/shop/address'], type='http', methods=['GET', 'POST'], auth="public", website=True, sitemap=False)
    def address(self, **post):
        # Override to inject dummy address values for pickup orders before Odoo validates them
        if post.get('submitted') and post.get('fulfilment_type') == 'pickup':
            if not post.get('street'): post['street'] = 'Store Pickup'
            if not post.get('city'): post['city'] = 'Local'
            if not post.get('zip'): post['zip'] = '00000'
            if not post.get('country_id'): 
                country = request.env['res.country'].sudo().search([], limit=1)
                post['country_id'] = str(country.id) if country else ''
            
            # Request.params must also be updated for Odoo 17 validation
            for k, v in post.items():
                if k in ['street', 'city', 'zip', 'country_id']:
                    if hasattr(request.params, 'update'):
                        try:
                            request.params[k] = v
                        except TypeError:
                            pass
                            
        return super(Dine360WebsiteSaleOnline, self).address(**post)
