# Copyright 2024 DOB
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).

from odoo.exceptions import AccessError
from odoo.tests import new_test_user
from odoo.tests.common import TransactionCase


class TestAccessApps(TransactionCase):
    """Tests for access_apps: access control to the Apps section.

    Validates: Requirement 6.1
    """

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.env = cls.env(
            context=dict(cls.env.context, tracking_disable=True, no_reset_password=True)
        )
        # Regular user without admin rights and without group_allow_apps
        cls.regular_user = new_test_user(
            cls.env,
            name="Regular User",
            login="test_regular_user_access_apps",
            groups="base.group_user",
        )

    def test_non_admin_cannot_read_ir_module_module(self):
        """WHEN a user without admin rights tries to access the Apps section,
        access_apps SHALL deny access.

        Validates: Requirement 6.1
        """
        # The module deactivates base.access_ir_module_module_group_user,
        # so only users in group_allow_apps can read ir.module.module.
        # A regular user (not in group_allow_apps) should get AccessError.
        with self.assertRaises(AccessError):
            self.env["ir.module.module"].with_user(self.regular_user).search([])

    def test_admin_can_read_ir_module_module(self):
        """WHEN the admin user (in group_allow_apps) accesses the Apps section,
        access_apps SHALL allow access.

        Validates: Requirement 6.1 (positive case)
        """
        # Admin is in group_allow_apps by default (see security XML)
        admin_user = self.env.ref("base.user_admin")
        modules = self.env["ir.module.module"].with_user(admin_user).search([], limit=1)
        # Should not raise; result may be empty or non-empty
        self.assertIsNotNone(modules)

    def test_non_admin_not_in_group_allow_apps(self):
        """WHEN a regular user is not in group_allow_apps,
        they SHALL NOT have access to ir.module.module.

        Validates: Requirement 6.1
        """
        group_allow_apps = self.env.ref("access_apps.group_allow_apps")
        self.assertNotIn(
            self.regular_user,
            group_allow_apps.users,
            "Regular user should not be in group_allow_apps",
        )
