# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import UserError, AccessError


class HrEmployeeSinWizard(models.TransientModel):
    _name = 'hr.employee.sin.wizard'
    _description = 'View/Edit Employee SIN'

    employee_id = fields.Many2one(
        'hr.employee',
        string='Employee',
        required=True,
        readonly=True,
    )
    employee_name = fields.Char(
        related='employee_id.name',
        string='Employee Name',
        readonly=True,
    )
    sin_number = fields.Char(
        string='Social Insurance Number',
        help='9-digit Social Insurance Number (Format: XXX-XXX-XXX)',
    )
    sin_number_formatted = fields.Char(
        string='SIN (Formatted)',
        compute='_compute_sin_formatted',
    )

    @api.depends('sin_number')
    def _compute_sin_formatted(self):
        for wizard in self:
            if wizard.sin_number:
                sin = wizard.sin_number.replace('-', '').replace(' ', '')
                if len(sin) == 9:
                    wizard.sin_number_formatted = f"{sin[0:3]}-{sin[3:6]}-{sin[6:9]}"
                else:
                    wizard.sin_number_formatted = wizard.sin_number
            else:
                wizard.sin_number_formatted = ''

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        # Check access rights
        if not self.env.user.has_group('hr.group_hr_manager') and \
           not self.env.user.has_group('account.group_account_manager'):
            raise AccessError('Only HR Managers and Accountants can view or edit SIN numbers.')
        return res

    def action_save(self):
        """Save the SIN number to the employee record"""
        self.ensure_one()
        
        # Double-check access rights
        if not self.env.user.has_group('hr.group_hr_manager') and \
           not self.env.user.has_group('account.group_account_manager'):
            raise AccessError('Only HR Managers and Accountants can edit SIN numbers.')
        
        # Format and validate SIN
        if self.sin_number:
            sin = self.sin_number.replace('-', '').replace(' ', '')
            if not sin.isdigit() or len(sin) != 9:
                raise UserError('Social Insurance Number must be exactly 9 digits.')
            # Store formatted
            formatted_sin = f"{sin[0:3]}-{sin[3:6]}-{sin[6:9]}"
            self.employee_id.write({'sin_number': formatted_sin})
        else:
            self.employee_id.write({'sin_number': False})
        
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': 'SIN Updated',
                'message': f'Social Insurance Number has been updated for {self.employee_id.name}',
                'type': 'success',
                'next': {'type': 'ir.actions.act_window_close'},
            }
        }
