from odoo import models, fields, api

class ResUsers(models.Model):
    _inherit = 'res.users'

    restaurant_role = fields.Selection([
        ('waiter', 'Waiter / Captain'),
        ('chef', 'Chef / Kitchen Staff'),
        ('cashier', 'Cashier'),
        ('manager', 'Manager'),
        ('admin', 'Admin / Owner'),
        ('store', 'Store Keeper'),
    ], string='Restaurant Role', help="Select the staff member's primary role.")

    @api.onchange('restaurant_role')
    def _onchange_restaurant_role(self):
        if not self.restaurant_role:
            return

        # Map roles to their XML IDs and REQUIRED Odoo Base groups to keep sections visible
        role_mapping = {
            'waiter': [
                'dine360_restaurant.group_restaurant_waiter',
                'base.group_user',
                'point_of_sale.group_pos_user'
            ],
            'chef': [
                'dine360_restaurant.group_restaurant_kitchen',
                'base.group_user'
            ],
            'cashier': [
                'dine360_restaurant.group_restaurant_cashier',
                'base.group_user',
                'point_of_sale.group_pos_user'
            ],
            'manager': [
                'dine360_restaurant.group_restaurant_manager',
                'base.group_user',
                'point_of_sale.group_pos_manager',
                'stock.group_stock_user'
            ],
            'admin': [
                'dine360_restaurant.group_restaurant_admin',
                'base.group_user',
                'point_of_sale.group_pos_manager',
                'stock.group_stock_manager',
                'base.group_system',
                'base.group_erp_manager'
            ],
            'store': [
                'dine360_restaurant.group_restaurant_store_keeper',
                'base.group_user',
                'stock.group_stock_user'
            ],
        }

        # 1. Clear existing restaurant groups (only in our custom category)
        category_staff = self.env.ref('dine360_restaurant.module_category_restaurant_staff', raise_if_not_found=False)
        if category_staff:
            restaurant_groups = self.env['res.groups'].search([('category_id', '=', category_staff.id)])
            self.groups_id = [(3, g.id) for g in restaurant_groups]

        # 2. Add the selected groups (one combined list of commands)
        group_xml_ids = role_mapping.get(self.restaurant_role, [])
        group_commands = []
        for xml_id in group_xml_ids:
            group = self.env.ref(xml_id, raise_if_not_found=False)
            if group:
                group_commands.append((4, group.id))
        
        self.groups_id = group_commands

