# Copyright 2025 Criptomart
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)

import logging

from odoo.http import request
from odoo.http import route

from odoo.addons.sale.controllers import portal as sale_portal

_logger = logging.getLogger(__name__)


class CustomerPortal(sale_portal.CustomerPortal):
    """Extend sale portal to include draft orders."""

    def _get_weekday_names(self):
        """Return translated weekday names (Monday first, Sunday last)."""
        _t = request.env._
        return [
            _t("Monday"),
            _t("Tuesday"),
            _t("Wednesday"),
            _t("Thursday"),
            _t("Friday"),
            _t("Saturday"),
            _t("Sunday"),
        ]

    def _prepare_orders_domain(self, partner):
        """Override to include draft and done orders."""
        return [
            ("message_partner_ids", "child_of", [partner.commercial_partner_id.id]),
            ("state", "in", ["draft", "sale", "done"]),  # Include draft orders
        ]

    @route(
        ["/my/orders", "/my/orders/page/<int:page>"],
        type="http",
        auth="user",
        website=True,
    )
    def portal_my_orders(self, **kwargs):
        """Override to add translated day names to context."""
        # Get values from parent
        values = self._prepare_sale_portal_rendering_values(
            quotation_page=False, **kwargs
        )

        # Add translated day names for pickup_day display
        values["day_names"] = self._get_weekday_names()

        request.session["my_orders_history"] = values["orders"].ids[:100]
        return request.render("sale.portal_my_orders", values)

    @route(["/my/orders/<int:order_id>"], type="http", auth="public", website=True)
    def portal_order_page(self, order_id, access_token=None, **kwargs):
        """Override to add translated day names for order detail page."""
        # Call parent to get response
        response = super().portal_order_page(
            order_id, access_token=access_token, **kwargs
        )

        # If it's a template render (not a redirect), add day_names to the context
        if hasattr(response, "qcontext"):
            response.qcontext["day_names"] = self._get_weekday_names()

        return response
