# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import http
from odoo.http import request

from odoo.addons.sale.controllers.portal import CustomerPortal


class CloverCustomerPortal(CustomerPortal):

    @http.route()
    def portal_order_page(
        self,
        order_id,
        report_type=None,
        access_token=None,
        message=False,
        download=False,
        payment_amount=None,
        amount_selection=None,
        **kw
    ):
        """Auto-inject payment_amount for confirmed orders with outstanding balance."""
        if payment_amount is None:
            try:
                order_sudo = self._document_check_access(
                    'sale.order', order_id, access_token=access_token,
                )
            except Exception:
                order_sudo = None

            if order_sudo:
                is_rental = getattr(order_sudo, 'is_rental_order', False)
                if (
                    order_sudo.state == 'sale'
                    and not is_rental
                    and order_sudo.amount_total > 0
                    and order_sudo.amount_paid < order_sudo.amount_total
                ):
                    payment_amount = order_sudo.amount_total - order_sudo.amount_paid

        return super().portal_order_page(
            order_id,
            report_type=report_type,
            access_token=access_token,
            message=message,
            download=download,
            payment_amount=payment_amount,
            amount_selection=amount_selection,
            **kw,
        )
