# -*- coding: utf-8 -*-
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import http
from odoo.http import request
from odoo.addons.website.controllers.main import Website
from werkzeug.utils import redirect as werkzeug_redirect

import logging

_logger = logging.getLogger(__name__)


class InventoryForm(http.Controller):

    @http.route(["/inventory/search"], type="http", auth="user", website=True)
    def inventory_form(self, **post):
        """Display inventory search form for authorized users."""
        user = request.env["res.users"].browse(request.uid)

        # Check if user has portal or internal access
        has_portal = user.has_group("base.group_portal")
        has_internal = user.has_group("base.group_user")

        if not has_portal and not has_internal:
            return werkzeug_redirect("/web")

        # Fetch active products available in POS
        products = (
            request.env["product.template"]
            .sudo()
            .search([("active", "=", True), ("available_in_pos", "=", True)])
        )
        vals = {"products": products}
        return request.render("website_search_products.web_list_products", vals)


class WebsiteController(Website):
    """Extend Website controller to redirect portal users after login."""

    @http.route(website=True, auth="public")
    def web_login(self, redirect=None, *args, **kw):
        """Handle login redirection based on user group."""
        response = super().web_login(redirect=redirect, *args, **kw)

        # Check if login was successful
        if not redirect and request.params.get("login_success"):
            user = request.env["res.users"].browse(request.uid)

            # Redirect internal users to web, others to inventory search
            if user.has_group("base.group_user"):
                # Keep original redirect for internal users
                redirect_url = "/web"
            else:
                # Redirect portal users to inventory search
                redirect_url = "/inventory/search"

            return werkzeug_redirect(redirect_url)

        return response
