from odoo import _, fields, models
from odoo.exceptions import UserError

# Only HR/Manager may set these -- an employee can read their own values
# (hr.employee's own record rules already allow that; these fields carry no
# groups= restriction, since groups= would block a regular employee from
# reading their OWN record too, not just from writing it) but any write from
# a non-HR/manager user touching these specific fields is rejected. Same
# "locked fields" idiom as xeno_leave's hr.leave write() override.
_XENO_LOCKED_PROBATION_FIELDS = {
    "xeno_probation_start", "xeno_probation_end", "xeno_probation_reviewer_id",
    "xeno_probation_mid_review_date", "xeno_probation_final_review_date",
}


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

    xeno_probation_start = fields.Date(string="Probation Start")
    xeno_probation_end = fields.Date(string="Probation End")
    xeno_probation_reviewer_id = fields.Many2one(
        "hr.employee", string="Probation Reviewer / Evaluator")
    xeno_probation_mid_review_date = fields.Date(string="Mid-Probation Review Date")
    xeno_probation_final_review_date = fields.Date(string="Final Evaluation Date")

    def write(self, vals):
        if not self.env.su and not self.env.user.has_group("hr.group_hr_manager"):
            locked_touched = set(vals) & _XENO_LOCKED_PROBATION_FIELDS
            if locked_touched:
                raise UserError(_(
                    "Only HR/Manager can set probation and evaluation dates."))
        return super().write(vals)


class HrEmployeePublic(models.Model):
    # Same hr.employee.public gotcha documented in hr_employee_birthday.py:
    # a regular employee's own-record reads (e.g. My Profile) go through
    # this delegate SQL-view model, which rejects any field not literally
    # mirrored here -- independent of the real field's own groups=.
    _inherit = "hr.employee.public"

    xeno_probation_start = fields.Date(related="employee_id.xeno_probation_start")
    xeno_probation_end = fields.Date(related="employee_id.xeno_probation_end")
    xeno_probation_reviewer_id = fields.Many2one(
        "hr.employee", related="employee_id.xeno_probation_reviewer_id")
    xeno_probation_mid_review_date = fields.Date(
        related="employee_id.xeno_probation_mid_review_date")
    xeno_probation_final_review_date = fields.Date(
        related="employee_id.xeno_probation_final_review_date")
