from datetime import timedelta

from odoo import fields, models


class HrEmployee(models.Model):
    _inherit = "hr.employee"

    xeno_is_welcome_back_today = fields.Boolean(
        compute="_compute_xeno_is_welcome_back_today",
        help="True on the employee's own first day back from an approved "
             "Maternity Leave (their leave's end date was yesterday). "
             "Deliberately not groups-restricted -- same reasoning as "
             "xeno_is_birthday_today (xeno_theme_slate): exposes only a "
             "yes/no fact about the logged-in employee's own record, "
             "never the underlying leave dates.",
    )

    def _compute_xeno_is_welcome_back_today(self):
        Leave = self.env["hr.leave"].sudo()
        leave_type = self.env["hr.leave.type"].sudo().search(
            [("name", "=", Leave._XENO_WELCOME_BACK_LEAVE_TYPE_NAME)], limit=1)
        back_today_ids = set()
        if leave_type:
            yesterday = fields.Date.context_today(self) - timedelta(days=1)
            leaves = Leave.search([
                ("employee_id", "in", self.ids),
                ("holiday_status_id", "=", leave_type.id),
                ("state", "=", "validate"),
                ("request_date_to", "=", yesterday),
            ])
            back_today_ids = set(leaves.employee_id.ids)
        for employee in self:
            employee.xeno_is_welcome_back_today = employee.id in back_today_ids


class HrEmployeePublic(models.Model):
    # Same "hr.employee.public rejects unknown fields regardless of
    # groups=" fix as xeno_theme_slate's xeno_is_birthday_today -- see
    # that model's comment for the full explanation (confirmed live via
    # the exact same "not available for employee public profiles" error).
    _inherit = "hr.employee.public"

    xeno_is_welcome_back_today = fields.Boolean(
        related="employee_id.xeno_is_welcome_back_today")
