from odoo import _, api, fields, models


class XenoResignation(models.Model):
    _name = "xeno.resignation"
    _description = "Employee Resignation / Separation"
    _inherit = ["mail.thread"]
    _order = "resign_date desc, id desc"

    employee_id = fields.Many2one(
        "hr.employee", required=True, tracking=True,
        domain="[('active', '=', True)]",
    )
    resign_type = fields.Selection(
        [
            ("resign", "Resign"),
            ("end_of_contract", "End of Contract"),
            ("discharge", "Discharge"),
            ("retirement", "Retirement"),
            ("terminate", "Terminate"),
            ("transfer", "Transfer"),
            ("pass_away", "Pass Away"),
        ],
        tracking=True,
    )
    resign_date = fields.Date(string="Resignation Date", tracking=True)
    start_date = fields.Date(string="Notice Period Start")
    save_date = fields.Date(string="Recorded On", default=fields.Date.context_today)
    cause = fields.Char()
    resignation_detail = fields.Text(string="Detail")
    attachment = fields.Binary(string="Attachment", attachment=True)
    attachment_filename = fields.Char(string="Attachment Filename")

    @api.model_create_multi
    def create(self, vals_list):
        records = super().create(vals_list)
        for record in records:
            employee = record.employee_id
            employee.write({"active": False})
            resign_type_label = dict(
                record._fields["resign_type"].selection
            ).get(record.resign_type) or _("unspecified")
            employee.message_post(
                body=_(
                    "Marked as resigned (%(resign_type)s) via resignation "
                    "record #%(record_id)s. Employee archived.",
                    resign_type=resign_type_label, record_id=record.id,
                )
            )
            if employee.user_id:
                employee.user_id.write({"active": False})
                employee.message_post(
                    body=_(
                        "Login access for %(user_name)s deactivated as part "
                        "of this resignation.",
                        user_name=employee.user_id.name,
                    )
                )
        return records
